如何将变量从远程PowerShell会话返回到本地PowerShell会话

时间:2016-06-29 18:20:50

标签: powershell

我有一个PowerShell脚本,可以创建一个新的PowerShell会话。我需要将在此会话中创建的无数变量中的一个变量返回到本地/调用会话。这是我的PowerShell脚本:

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)

当脚本执行Write-Host ($var2)时,它不会打印$ var2的任何值。如何将$ var2返回到本地会话?

1 个答案:

答案 0 :(得分:3)

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

只需使用Write-Outputreturn从会话的脚本块中返回变量,或者只是在我演示的其他命令中使用该变量。 Invoke-Command的返回值将是scriptblock写入管道的任何内容。