用于验证远程操作的本地变量

Tal*_*nez 0 powershell powershell-remoting

我正在尝试验证远程计算机是否可以连接到特定端口上的另一台计算机

伪代码

$RemoteSession = New-PSSession -ComputerName MyRemoteVM

Invoke-Command -Session $RemoteSession -ScriptBlock {$RsTestResults = New-Object System.Net.Sockets.TcpClient -Argument 2ndRemoteVM , 2ndRemoteVMPort}
Run Code Online (Sandbox Code Playgroud)

但是,我似乎无法获得该测试的结果,我尝试添加另一个 Invoke-Command,如下所示,但这没有帮助

$LocalResults = Invoke-Command -ScriptBlock {$RsTestResults}
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

San*_*zon 5

当你这样做时:

Invoke-Command -Session $RemoteSession -ScriptBlock {
    $RsTestResults = New-Object System.Net.Sockets.TcpClient -ArgumentList 2ndRemoteVM, 2ndRemoteVMPort
}
Run Code Online (Sandbox Code Playgroud)

该变量$RsTestResults正在远程主机上创建,其范围将称为主机。如果您希望将结果System.Net.Sockets.TcpClient存储在本地主机上,则需要存储Invoke-Command如下结果:

$RsTestResults = Invoke-Command -Session $RemoteSession -ScriptBlock {
    New-Object System.Net.Sockets.TcpClient -ArgumentList 2ndRemoteVM, 2ndRemoteVMPort
}
Run Code Online (Sandbox Code Playgroud)

编辑

解释您收到的错误消息:

PS > New-Object System.Net.Sockets.TcpClient -ArgumentList $null, $null
New-Object : Exception calling ".ctor" with "2" argument(s): "The requested address is not valid in its context xxx.xxx.xxx.xxx:0"
Run Code Online (Sandbox Code Playgroud)

IPAddress这意味着,和的变量Port永远不会传递给Invoke-Command.

您有 2 个选项可将这些变量传递给 cmdlet,一个是 with $using:variableName,另一个是 with -ArgumentList

假设你有2个局部变量,例如:

$ipAddress = $csv.IPAddress
$port = $csv.Port
Run Code Online (Sandbox Code Playgroud)
$RsTestResults = Invoke-Command -Session $RemoteSession -ScriptBlock {
    New-Object System.Net.Sockets.TcpClient -ArgumentList $using:ipAddress, $using:port
}
Run Code Online (Sandbox Code Playgroud)
$RsTestResults = Invoke-Command -Session $RemoteSession -ScriptBlock {
    param($ipAddress, $port)
    New-Object System.Net.Sockets.TcpClient -ArgumentList $ipAddress, $port
} -ArgumentList $ipAddress, $port
Run Code Online (Sandbox Code Playgroud)