f3n*_*r1r 0 variables powershell null invoke-command
$server = "SOME_SERVER"
$target = "8.8.8.8"
Invoke-Command -ComputerName $server -ScriptBlock { Test-Connection -ComputerName $target }
Run Code Online (Sandbox Code Playgroud)
所以我有这个代码,它给我一个错误
无法验证参数'ComputerName'的参数.参数为null或空.提供非null或空的参数,然后再次尝试该命令.
奇怪的是,如果我换$target到8.8.8.8最后一行,一切都很好.
有人可以向我解释一下吗?我一直在努力争取一个小时,并搜索互联网寻找答案,但没有找到任何解决方案.这是PowerShell中的某种错误吗?
BTW - 如果我调用$target它,它给了我8.8.8.8,类型是String,所以......
您的本地变量在远程连接中不可用.
您需要将其作为参数传递:
... -ArgumentList $target -ScriptBlock { param($target) ...
Run Code Online (Sandbox Code Playgroud)
或利用$using范围:
... Test-Connection -ComputerName $using:target ...
Run Code Online (Sandbox Code Playgroud)