如何将变量从远程 PowerShell 会话返回到本地 PowerShell 会话 [英] How to return a variable from a remote PowerShell session to a local PowerShell session
问题描述
我有一个 PowerShell 脚本,用于创建新的 PowerShell 会话.我需要将此会话中创建的无数变量中的一个变量返回到本地/调用会话.这是我的 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)
当脚本执行 Write-Host ($var2)
时,它不会为 $var2 打印任何值.如何将 $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
只需使用 Write-Output
或 return
从会话的脚本块中返回变量,或者像我演示的那样在另一个命令中使用该变量.Invoke-Command
的返回值将是脚本块写入管道的任何内容.
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.
这篇关于如何将变量从远程 PowerShell 会话返回到本地 PowerShell 会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!