Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a variable from a remote PowerShell session to a local PowerShell session

Tags:

powershell

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?

like image 800
skyline01 Avatar asked Sep 03 '25 01:09

skyline01


1 Answers

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.

like image 65
briantist Avatar answered Sep 05 '25 00:09

briantist