I have a PowerShell script that creates a new PowerShell session. I need to return one of the variables from the myriad of variables that is created in this session to the local / calling session. Here is my PowerShell script:
param
(
[string]$user,
[string]$password
)
$secure_password = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential $user, $secure_password
$new_session = New-PSSession -Credential $cred
$script = {
$var1 = 0
$var2 = a
}
Invoke-Command -Session $new_session -ScriptBlock $script
Write-Host ($var2)
When the script executes Write-Host ($var2)
, it doesn't print any value for $var2. How can I return $var2 to the local session?
param
(
[string]$user,
[string]$password
)
$secure_password = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential $user, $secure_password
$new_session = New-PSSession -Credential $cred
$script = {
$var1 = 0
$var2 = a
$var2
}
$varFromSession = Invoke-Command -Session $new_session -ScriptBlock $script
Write-Host $varFromSession
Just return the variable from the session's scriptblock, either with Write-Output
or return
or just use the variable in another command as I've demonstrated. The return value of Invoke-Command
will be whatever the scriptblock wrote to the pipeline.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With