【问题标题】:Local Variable to validate remote operation验证远程操作的局部变量
【发布时间】:2021-12-03 06:24:52
【问题描述】:

我正在尝试验证远程机器是否可以通过特定端口连接到另一台机器

伪代码

$RemoteSession = New-PSSession -ComputerName MyRemoteVM

Invoke-Command -Session $RemoteSession -ScriptBlock {$RsTestResults = New-Object System.Net.Sockets.TcpClient -Argument 2ndRemoteVM , 2ndRemoteVMPort}

但是,我似乎无法获得该测试的结果 我已经尝试添加另一个像下面这样的 Invoke-Command,但它没有帮助

$LocalResults = Invoke-Command -ScriptBlock {$RsTestResults}

有什么想法吗?

【问题讨论】:

    标签: powershell powershell-remoting


    【解决方案1】:

    当你这样做时:

    Invoke-Command -Session $RemoteSession -ScriptBlock {
        $RsTestResults = New-Object System.Net.Sockets.TcpClient -ArgumentList 2ndRemoteVM, 2ndRemoteVMPort
    }
    

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

    $RsTestResults = Invoke-Command -Session $RemoteSession -ScriptBlock {
        New-Object System.Net.Sockets.TcpClient -ArgumentList 2ndRemoteVM, 2ndRemoteVMPort
    }
    

    编辑

    解释您收到的错误消息:

    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"
    

    这意味着IPAddressPort 的变量永远不会传递给Invoke-Command

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

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

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

    【讨论】:

    • 这行不通 - powershell 将序列化生成的对象,您将无法在本地会话中与客户端交互。
    • @MathiasR.Jessen 你是对的,由于序列化,对象会丢失它的方法。我应该指出这一点,我的错。但是,如果 OP 只是想知道端口是否打开,我认为这就足够了。
    • 感谢大家的回复。但是,我仍然没有得到它(提前抱歉)
    • 感谢大家的回复。但是,我仍然没有得到它(提前抱歉)。当我将代码更改为: $RsTestResults = Invoke-Command -Session $RemoteSession - ScriptBlock {New-Object System.Net.Sockets.TcpClient - Argument 2ndRemoteVM, 2ndRemotePort} 我收到一个错误 New-Object: Exception calling ".ctor"带有“2”个参数“请求的地址在其上下文中无效[IP地址]:0
    • @TallKewlOnez 2ndRemoteVM2ndRemoteVMPort 是硬编码值还是传递给 Invoke-Command 的变量?如果是这样,你如何传递这些变量?另一方面,从阅读错误信息来看,- Argument 中似乎多了一个空格(应该是-Argument)。
    猜你喜欢
    • 1970-01-01
    • 2012-12-23
    • 2021-10-22
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    • 2022-01-27
    • 1970-01-01
    相关资源
    最近更新 更多