PowerShell Invoke-Command -AsJob

时间:2014-07-10 13:50:12

标签: powershell

我写的脚本很长,但除了一个问题外,工作正常。当我为同一jobs提供更多$Server时,它只提交一份工作而且不会为同一$Server执行第二份或第三份工作。

输入来自以下格式的CSV文件:

\\domain\SHARE\Target3, 0
BELSFBRUS0131, E:\DEPARTMENTS\CBR\SHARE\Target2, 0
BELSFBRUS0131, E:\DEPARTMENTS\CBR\SHARE\Target4, 0

在上面的示例中,脚本仅启动2个作业,一个用于UNC路径Target3,另一个用于Target2上的BELSFBRUS0131,这些都可以正常执行。但是Target4没有为同一台服务器启动任务......这可能是Invoke-Command限制只对每台服务器启动一次吗?

感谢您的帮助。

这是脚本的重要部分(由于最多30.000行,我限制它):

Foreach ($_ in $File) {

# Starting jobs

    if (($Server -eq "UNC") -or ($Server -eq "$env:COMPUTERNAME")) {
        Write-Host "$(Get-TimeStamp) $env:COMPUTERNAME > Start job: local > $Server, $Target, $OlderThanDays, $LogFolder, $CleanFolders" -ForegroundColor Gray
        $arrayAllJobs += Start-Job -ScriptBlock $JobCall -ArgumentList ($Target, $OlderThanDays, $Server, $LogFolder, $CleanFolders) -Name DelFiles
    }
    else {
          Write-Host "$(Get-TimeStamp) $env:COMPUTERNAME > Start job: Remote > $Server, $Target, $OlderThanDays, $LogFolder, $CleanFolders" -ForegroundColor Gray        
          $arrayAllJobs += Invoke-Command -ScriptBlock $JobCall -ArgumentList ($Target, $OlderThanDays, $Server, $LogFolder, $CleanFolders) -ComputerName "$Server.grouphc.net" -Authentication Credssp -Credential $Credentials -AsJob -JobName DelFiles
    }  
}
#__________________________________________________________________________________________________________________________________
# Checking jobs

Write-Host "`n$(Get-TimeStamp) $env:COMPUTERNAME > Waiting for all jobs to finish.." -ForegroundColor Cyan; Wait-Job -Job $arrayAllJobs
Write-Host "`n$(Get-TimeStamp) $env:COMPUTERNAME > The targets were:" -ForegroundColor Cyan; $arrayAllPaths | Format-List

foreach ($Job in $arrayAllJobs) {
    if ($job.State -ne 'Completed') {
        # Write-Host ($Job.ChildJobs[0].JobStateInfo.Reason.Message) -ForegroundColor Red
        $arrayJobError += $Job.ChildJobs[0].JobStateInfo.Reason.Message
        $HTMLarrayJobError += $Job.ChildJobs[0].JobStateInfo.Reason.Message +"<br>"
    } 
    #<# Reported success:
    else {
        Write-Host (Receive-Job $Job) -ForegroundColor Green 
    } #>
}

2 个答案:

答案 0 :(得分:0)

我怀疑它与您使用相同的JobName创建所有作业的事实有关:

 Invoke-Command -ScriptBlock $JobCall -ArgumentList ($Target, $OlderThanDays, $Server, $LogFolder, $CleanFolders) -ComputerName "$Server.grouphc.net" -Authentication Credssp -Credential $Credentials -AsJob -JobName DelFiles

所以你试图在同一台服务器上创建两个同名的作业。

答案 1 :(得分:0)

我在我的脚本中犯了一个错误,这就是为什么seconde服务器没有到达循环的原因。我很抱歉,不好意思。