从 Start-Job 调用获取输出

Getting output from a Start-Job invocation

我有以下代码可以工作,因为它创建了多个作业和 运行 阵列中所有计算机 ($SMSMembers) 上脚本块中的内容。问题是它没有返回任何有意义的输出,我可以用它来确定代码 运行 是否成功。我已经尝试了大约 100 种不同的东西,我已经用谷歌搜索过,但 none 的解决方案似乎对我有用。这是我正在尝试 运行 我认为应该根据我在 Whosebug 上看到的其他帖子工作的代码。

$SMSMembers = @("computer1","computer2","computer3")
$output = @()
foreach ($compName in $SMSMembers) {
    $scriptblock = {
        $file = {"test"}
        $filepath = "\$using:compName\c$\scripts\NEWFILE.txt"
        $file | Out-File -FilePath $filepath
        Start-Sleep -Seconds 5
        Remove-Item $filepath
    }
    $output += Start-Job -ScriptBlock $scriptblock | Get-Job | Receive-Job
}
Get-Job | Wait-Job
foreach ($item in $output) {
    Write-Host $item
}

除了将文件复制到远程计算机然后将其删除之外,此脚本并没有做太多事情。如果工作成功与否,我只想获得输出。就像我说的那样,这段代码可以正常工作,我只是没有得到反馈。

我的最终目标是能够向一组计算机 ($SMSMembers) 发送命令并使用此代码请求当前用户并取回用户名输入:

$user = gwmi Win32_ComputerSystem -Comp $compName |
        select Username -ExpandProperty Username

看看下面的代码,我想你应该能弄明白。

>  Get-job | Receive-Job 2>&1 >> c:\output.log

2>&1 >> 收集来自 Get-Job | Receive-Job 的所有输出它应该与 start-job

的工作类似

您创建作业,获取作业信息,然后在作业完成之前接连接收作业。相反,收集作业信息,然后在循环外等待作业完成,并在作业完成时接收输出。

$SMSMembers = @("computer1","computer2","computer3")
$scriptblock = {
    $file = {"test"}
    $filepath = "\$using:compName\c$\scripts\NEWFILE.txt"
    $file | out-file -FilePath $filepath
    Start-Sleep -Seconds 5
    remove-item $filepath
}
$Jobs = foreach($compName in $SMSMembers){
    Start-Job -ScriptBlock $scriptblock
}
Wait-Job $Jobs
$Output = Receive-Job $Jobs
foreach ($item in $output){
    write-host $item
}

编辑: 稍微修改了脚本,这样我就不会随意复制文件了,但它的功能应该还是一样的。然后用预期的结果测试它:

$SMSMembers = @("computer1","computer2","computer3")
$scriptblock = {
    $RndDly=Get-Random -Minimum 10 -Maximum 45
    start-sleep -Seconds $RndDly
    "Slept $RndDly, then completed for $using:compname"
    }
$Jobs = foreach($compName in $SMSMembers){
    Start-Job -ScriptBlock $scriptblock
}
Wait-Job $Jobs
$Output = Receive-Job $Jobs
foreach ($item in $output){
    write-host $item
}

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                  
--     ----            -------------   -----         -----------     --------             -------                  
1      Job1            BackgroundJob   Completed     True            localhost            ...                      
3      Job3            BackgroundJob   Completed     True            localhost            ...                      
5      Job5            BackgroundJob   Completed     True            localhost            ...                      
Slept 30, then completed for computer1
Slept 27, then completed for computer2
Slept 11, then completed for computer3