Powershell 检索作业给出 "cannot index into null array error"

Powershell Retrieve-Job gives "cannot index into null array error"

我正在尝试使用以下脚本测试两台 PC 是否已连接

$array ='PC1','PC2'


for ($i=0; $i -lt $array.length; $i++)  {

     Start-Job –Name TestConnection$i –Scriptblock {

            if(test-connection $array[$i] -count 1 -quiet){
               write-host Success
            }

            else { write-host No connection
            }

    }

}

当我尝试为任何一个执行 Receive-Job 时,我得到 "Cannot index into a null array"。 我做错了什么?

您需要传入 PC 名称作为参数,因为数组在脚本块的上下文中不存在,如下所示:

$array ='PC1','PC2'

for ($i=0; $i -lt $array.Length; $i++) {

    Start-Job –Name TestConnection –Scriptblock { 
        param($pcName)

        if(Test-Connection $pcName -Count 1 -Quiet) {
            Write-Host Success
        } else {
            Write-Host No connection
        }           
    } -ArgumentList $array[$i]
}

您必须通过 Start-Job Cmdlet 通过 -ArgumentList 传递 $i(和任何其他变量),因为您的脚本块 运行 在完全不同的 powershell 主机中并且不无法访问启动作业的 shell 中的任何内容。

即使您的脚本块存在于原始代码中,Powershell 也不会扩展其中的任何变量,直到它在其他主机中执行代码。您可以在脚本块的开头定义 param() 以使用您通过 -ArgumentList

传递的变量