Powershell启动作业作业未完成

Powershell启动作业作业未完成,powershell,start-job,Powershell,Start Job,我在开展工作时遇到了一些困难,我很难找到问题所在。如果不是所有的话,大多数工作都没有完成。以下代码在未作为作业启动时工作正常 $timer = [System.Diagnostics.Stopwatch]::StartNew() $allServers = Import-Csv "C:\temp\input.csv" $password = GC "D:\Stored Credentials\PW" | ConvertTo-SecureString $allServers | % {

我在开展工作时遇到了一些困难,我很难找到问题所在。如果不是所有的话,大多数工作都没有完成。以下代码在未作为作业启动时工作正常

$timer = [System.Diagnostics.Stopwatch]::StartNew()
$allServers = Import-Csv "C:\temp\input.csv"
$password = GC "D:\Stored Credentials\PW" | ConvertTo-SecureString


$allServers | % {
    Start-Job -ArgumentList $_.ComputerName,$_.Domain -ScriptBlock {
        param($sv,$dm)
        $out = @()

        #Determine credential to use and create password
        $password = GC "D:\Stored Credentials\PW" | ConvertTo-SecureString
        switch ($dm) {
            USA {$user = GC "D:\Stored Credentials\MIG"}
            DEVSUB {$user = GC "D:\Stored Credentials\DEVSUB"}
            default {$cred = ""}
            }
        $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user,$password

        #Query total cpus
        $cpu = ((GWMI win32_processor -ComputerName $sv -Credential $cred).NumberOfLogicalProcessors | Measure-Object).Count

        $outData = New-Object PSObject
        $outData | Add-Member -Type NoteProperty -Name "ComputerName" -Value $sv
        $outData | Add-Member -Type NoteProperty -Name "#CPU" -Value $cpu

        $out += $outData
        return $out
        }
    }

while (((Get-Job).State -contains "Running") -and $timer.Elapsed.TotalSeconds -lt 60) {
    Start-Sleep -Seconds 10
    Write-Host "Waiting for all jobs to complete"
    }
Get-Job | Receive-Job | Select-Object -Property * -ExcludeProperty RunspaceId | Out-GridView

out+=$outData有什么用;返回$out
?看起来您认为这段代码是在循环中执行的,但事实并非如此。外部foreach对象启动多个
独立的
作业。每一个都创建一个
$outData
。您可以将最后一段代码简化为:

$outData = New-Object PSObject
$outData | Add-Member -Type NoteProperty -Name "ComputerName" -Value $sv
$outData | Add-Member -Type NoteProperty -Name "#CPU" -Value $cpu
$outData
我将进一步简化(在V3上)

顺便说一句,如果您给属性命名为
#CPU
,那么访问它会很麻烦,因为您必须引用属性名称,例如:
$obj.#CPU'

您还可以将等待循环简化为:

$jobs = $allServers | % {
    Start-Job -ArgumentList $_.ComputerName,$_.Domain -ScriptBlock { ... }
} 
Wait-Job $jobs -Timeout 60
Receive-Job $jobs | Select -Property * -ExcludeProperty RunspaceId | Out-GridView
虽然

$jobs = $allServers | % {
    Start-Job -ArgumentList $_.ComputerName,$_.Domain -ScriptBlock { ... }
} 
Wait-Job $jobs -Timeout 60
Receive-Job $jobs | Select -Property * -ExcludeProperty RunspaceId | Out-GridView