Powershell在多个服务器上使用-Asjob运行invoke-command,但在本地记录完成日志



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

这是我正在测试的示例代码,脚本运行良好,但是"完成";日志文件立即生成,而不是在每个服务器完成后生成。

$VerbosePreference = 'Continue'
$servers = Get-Content -Path f:tempservers.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:temptestfile1.txt
Start-Sleep -Seconds 20
echo testfile2 > f:temptestfile2.txt
Start-Sleep -Seconds 20
echo testfile3 > f:temptestfile3.txt
echo DONE} > f:temp$server.done.txt -Asjob
} 

感谢

删除Invoke-Command { ... }之后的重定向操作符—否则您将重定向产生的作业对象到file,而不是从作业输出—相反,将所有作业对象收集到变量$jobs:

$VerbosePreference = 'Continue'
$servers = Get-Content -Path f:tempservers.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:temptestfile1.txt
Start-Sleep -Seconds 20
echo testfile2 > f:temptestfile2.txt
Start-Sleep -Seconds 20
echo testfile3 > f:temptestfile3.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
}

最新更新