Powershell Start-Job工作未完成

时间:2014-04-30 19:58:55

标签: powershell start-job

我在找工作时遇到一些困难,而我却无法找到问题所在。大多数(如果不是全部)工作都没有完成。以下代码在未作为工作开始时正常工作。

$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

1 个答案:

答案 0 :(得分:1)

out += $outData; return $out的内容是什么?看来你认为这段代码是在一个循环中执行但它不是。外部foreach-object启动多个independent个作业。每个人创建一个$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上)

[pscustomobject]@{ComputerName = $sv; CpuCount = $cpu}

顺便说一句,如果您将属性命名为#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

虽然