Basically, I have a yaml config file, where I want to declare env variables. My PS Script, is supposed to read these and declare them inside a function.
so I have something like:
config.yaml:
env:
var1: "hello"
var2: "world"
step:
script:
- Write-Host "$env:var1, $env:var2"
script.ps1 (abbreviated)
$config = ConvertFrom-Yaml (Get-Content $yamlFilePath -Raw)
$session = New-PSSession -ComputerName $remoteHost -Credential $creds
foreach($key in $config.env.Keys){
Invoke-Command -Session $Session -ScriptBlock {
param (
[string]$Name,
[string]$Value
)
Set-Item -Path "env:$Name" -Value $Value
} -ArgumentList $key, $config.env[$key]
}
The user is also supposed to be able to provide a script to be run on the remote host. This script must be able to access the variables I defined in the session.
Which I do like this:
$lines = $config.script
foreach($line in $lines){
Invoke-Command -Session $session -ScriptBlock {
param([string]$Line)
Invoke-Expression $Line
} -ArgumentList $line
}
My problem is, that the $Line isn’t being evaluated correctly. What ends up executing on the remote host is the line as is: Write-Host “$env:var1, $env:var2” instead of “Write-Host “Hello, World”.
Is there a way to do this? Or should I look into alternative ways to go about it?
I ended solving this, by realizing that this wasn’t a code issue. It was me being a dummy issue. I was calling sqlcmd on the remote host, but forgot to add the instance!
The variables were being declared and read correctly all along!