Search code examples
powershellpowershell-remoting

Local Variable to validate remote operation


I am trying to validate that a remote machine can connect to another machine on a specific port

Pseudo Code

$RemoteSession = New-PSSession -ComputerName MyRemoteVM

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

However, I can't seem to get the results of that test I have tried adding another Invoke-Command like below, but it is not helping

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

any thoughts?


Solution

  • When you do:

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

    The variable $RsTestResults is being created on the remote host and its scope will be said host. If you want the results of System.Net.Sockets.TcpClient to be stored on your local host, you would need to store the results of Invoke-Command like below:

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

    Edit

    To explain the error message you're getting:

    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"
    

    Which means, the variables for IPAddress and Port are never being passed to Invoke-Command.

    You have 2 options to pass those variables to the cmdlet, one is with $using:variableName and the other is with -ArgumentList.

    Assuming you have 2 local variables, for example:

    $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