0

我在启动工作时遇到了一些困难,而且我很难找出问题所在。大多数(如果不是全部)工作都没有完成。下面的代码在没有作为工作开始时正常工作。

$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
4

1 回答 1

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

虽然

于 2014-04-30T21:58:34.217 回答