Powershell 运行 在多台服务器上使用 -Asjob 调用命令,但在本地记录完成日志

Powershell running invoke-command on several servers using -Asjob but log completion log locally

我正在尝试 运行 一个 powershell 脚本,它可以在一堆远程服务器上安装一些软件。 我正在使用 -Asjob 选项来同步 运行 它们。 我还使用 for 循环 运行 每个服务器上的远程命令,但我想在 本地写一个“完成”日志文件 运行 脚本 在每个服务器完成命令时准确通知我。

这是我正在测试的示例代码,脚本 运行 没问题,但“完成”日志文件会立即生成,而不是在每个服务器完成时生成。

$VerbosePreference = 'Continue'
$servers = Get-Content -Path f:\temp\servers.txt

foreach($server in $servers) {
    Write-Verbose "Start batch file as a job on $server"
    Start-Sleep -Seconds 3
    Invoke-Command -ComputerName $server -ScriptBlock {
    echo testfile1 > f:\temp\testfile1.txt
    Start-Sleep -Seconds 20
    echo testfile2 > f:\temp\testfile2.txt
    Start-Sleep -Seconds 20
    echo testfile3 > f:\temp\testfile3.txt
    echo DONE} > f:\temp$server.done.txt -Asjob
} 

谢谢

删除 Invoke-Command { ... } 之后的重定向运算符 - 否则你会将生成的 作业对象 重定向到文件,而不是作业的输出 - 相反,收集所有作业对象到一个变量 $jobs:

$VerbosePreference = 'Continue'
$servers = Get-Content -Path f:\temp\servers.txt

$jobs = foreach($server in $servers) {
    Write-Verbose "Start batch file as a job on $server"
    Start-Sleep -Seconds 3
    Invoke-Command -ComputerName $server -ScriptBlock {
    echo testfile1 > f:\temp\testfile1.txt
    Start-Sleep -Seconds 20
    echo testfile2 > f:\temp\testfile2.txt
    Start-Sleep -Seconds 20
    echo testfile3 > f:\temp\testfile3.txt
    echo DONE} -Asjob
}

现在我们已经启动了所有远程作业并收集了相关的作业对象,我们只需要等待然后收集输出:

foreach($job in $jobs){
    # Wait for jobs to finish, retrieve their output
    $jobOutput = $job |Receive-Job -Wait 

    # Grab the remote server name from the output
    $server = $jobOutput |ForEach-Object PSComputerName |Select -First 1

    # Write output to file
    $jobOutput > f:\temp$server.done.txt
}