从 Start-Job 调用获取输出

Spe*_*r A 1 windows powershell multithreading start-job

我有以下代码,它可以创建多个作业并在数组 ( $SMSMembers) 中的所有计算机上运行脚本块内的内容。问题是它没有给出任何有意义的输出,我可以用它来确定代码是否成功运行。我已经尝试了大约 100 种不同的方法,但没有一个解决方案对我有用。这是我试图运行的代码,我认为根据我在 StackOverflow 上看到的其他帖子应该可以工作。

$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
}
Run Code Online (Sandbox Code Playgroud)

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

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

$user = gwmi Win32_ComputerSystem -Comp $compName |
        select Username -ExpandProperty Username
Run Code Online (Sandbox Code Playgroud)

The*_*ian 5

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

$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
}
Run Code Online (Sandbox Code Playgroud)

编辑:稍微修改了脚本,这样我就不会随机复制文件,但它的功能仍然应该相同。然后测试了一下,得到了预期的结果:

$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
Run Code Online (Sandbox Code Playgroud)