我有一个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返回到本地会话?
答案 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-Output
或return
从会话的脚本块中返回变量,或者只是在我演示的其他命令中使用该变量。 Invoke-Command
的返回值将是scriptblock写入管道的任何内容。