0
$server = "SOME_SERVER"
$target = "8.8.8.8"
Invoke-Command -ComputerName $server -ScriptBlock { Test-Connection -ComputerName $target }

So I have this code and it's throwing me an error

Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Supply an argument that is not null or empty and then try the command again.

Strange thing is that if I change $target to 8.8.8.8 in last line, everything's fine.

Can someone explain this to me, please? I've been struggling with this for like an hour and searched internet looking for an answer but didn't find any solution. Is this some kind of a bug in PowerShell?

BTW - if I invoke $target, it's giving me 8.8.8.8 and the type is String, so...

Jacob Colvin
  • 2,625
  • 1
  • 17
  • 36
f3nr1r
  • 21
  • 7

3 Answers3

5

Your local variables are not available in a remote connection.

You need to either pass it as an argument:

... -ArgumentList $target -ScriptBlock { param($target) ...

or utilize the $using scope:

... Test-Connection -ComputerName $using:target ...
Maximilian Burszley
  • 18,243
  • 4
  • 34
  • 63
2

Invoke-Command does not pass your local variables to the target system. $server does not have $target defined, thus the Test-Connection command will fail since $target -eq $null, as the error states. To fix this, you can pass the remote server an argument, using the -ArgumentList parameter. For example:

Invoke-Command -ComputerName $server -ScriptBlock { Test-Connection -ComputerName $args[0] } -ArgumentList $target
mklement0
  • 382,024
  • 64
  • 607
  • 775
Jacob Colvin
  • 2,625
  • 1
  • 17
  • 36
1

I'd use a structured approach:

$source = 'myserver'
$destination = '8.8.8.8'

Invoke-Command -ComputerName $source -Credential (Get-Credential) -ScriptBlock {
    param(
        [Parameter()]
        [string]$destination
    )    
    Test-Connection $destination
} -ArgumentList $destination

The -Credential parameter is useful if the current user lacks the required privileges.

mklement0
  • 382,024
  • 64
  • 607
  • 775
Zangetsu
  • 11
  • 2