同步变量不适用于远程运行空间

时间:2016-06-22 17:08:39

标签: c# powershell runspace

下面的

代码将演示Runnspaces的Synchronized变量的用法。只要可以访问,就可以使用$ ComputerName的任何ip / hostname,通过Enter-PSSession验证Powershell远程处理,并且还将$ ComputerName的凭据添加到Windows Credential Manager作为主机。

Get-Runspace | ? Id -NE 1 | % { $_.close() ; $_.dispose() }
$Runspace = $powerShell = $connectionInfo = $handle = $hash = $null 
$ComputerName = '192.168.0.3'

$hash = [hashtable]::Synchronized(@{})
$hash.One = 1

Write-host ('Value of $Hash.One before background runspace is {0}' -f $hash.one) -ForegroundColor Green -BackgroundColor Black
$Uri = New-Object System.Uri("http://$($ComputerName):5985/wsman")
$connectionInfo = New-Object System.Management.Automation.Runspaces.WSManConnectionInfo -ArgumentList $Uri
$connectionInfo.AuthenticationMechanism = [System.Management.Automation.Runspaces.AuthenticationMechanism]::Negotiate
$connectionInfo.OpenTimeout = 3000

$Runspace = [runspacefactory]::CreateRunspace($connectionInfo) # don't work
#$Runspace = [runspacefactory]::CreateRunspace() # works

$runspace.Open()
$runspace.SessionStateProxy.SetVariable('Hash',$hash)

$powershell = [powershell]::Create()
$powershell.Runspace = $runspace

$powershell.AddScript({
    $hash.one++
}) | Out-Null #The Out-Null at the end is used to prevent the output of the object that occurs.

$handle = $powershell.BeginInvoke()
While (-Not $handle.IsCompleted) {
    Start-Sleep -Milliseconds 100
}

$powershell.EndInvoke($handle)
$runspace.Close()
$powershell.Dispose()

Write-host ('Value of $Hash.One after background runspace is {0}' -f $hash.one) -ForegroundColor Green -BackgroundColor Black

我一更换:

$Runspace = [runspacefactory]::CreateRunspace()

$Runspace = [runspacefactory]::CreateRunspace($connectionInfo)

(因为我想在远程计算机上执行代码),同步变量$ hash不会更新。谁知道我错过了什么?此功能非常重要且有用,我需要它才能使其适用于远程运行空间。

0 个答案:

没有答案
相关问题