【问题标题】:Test-Connection and Variable [duplicate]测试连接和变量
【发布时间】:2018-05-23 05:30:16
【问题描述】:
$server = "SOME_SERVER"
$target = "8.8.8.8"
Invoke-Command -ComputerName $server -ScriptBlock { Test-Connection -ComputerName $target }

所以我有这个代码,它给我一个错误

无法验证参数“计算机名”上的参数。论据是 为空或为空。提供一个不为 null 或空的参数,然后 再次尝试该命令。

奇怪的是,如果我在最后一行将$target 更改为8.8.8.8,一切都很好。

谁能给我解释一下,好吗?我已经为此苦苦挣扎了一个小时,并在互联网上搜索以寻找答案,但没有找到任何解决方案。这是PowerShell中的某种错误吗?

顺便说一句 - 如果我调用 $target,它会给我 8.8.8.8 并且类型是字符串,所以......

【问题讨论】:

    标签: powershell variables null invoke-command


    【解决方案1】:

    您的本地变量在远程连接中不可用。

    您需要将其作为参数传递:

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

    或使用$using scope

    ... Test-Connection -ComputerName $using:target ...
    

    【讨论】:

      【解决方案2】:

      Invoke-Command 不会将本地变量传递给目标系统。 $server 没有定义$target,因此Test-Connection 命令将在$target -eq $null 之后失败,如错误所述。要解决此问题,您可以使用-ArgumentList 参数向远程服务器传递一个参数。例如:

      Invoke-Command -ComputerName $server -ScriptBlock { Test-Connection -ComputerName $args[0] } -ArgumentList $target
      

      【讨论】:

        【解决方案3】:

        我会使用结构化方法:

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

        如果当前用户缺乏所需的权限,-Credential 参数很有用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-06-27
          • 2010-12-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-05-02
          • 1970-01-01
          相关资源
          最近更新 更多