Powershell Script Running Slowly

前端 未结 4 1457
眼角桃花
眼角桃花 2021-01-28 07:46

I\'m writing a script to check the version on about 15 remote servers and the script is taking much longer to execute than I would expect.

$listServers = @(\"com         


        
4条回答
  •  我在风中等你
    2021-01-28 08:02

    Yeah, I think using jobs is the way to go. WMI calls can take a long time, especially if you run into a host or two that aren't responding.

    Maybe consider something like this:

    $listServers = @((1..15 | % {"compName$_"}))
    $jobList = @()
    
    $JavaBlock = {
    function checkServer ($serverName) {
        $returnValue = Get-WmiObject -computerName $serverName -Class Win32_Product -Credential $cred -Filter "Name like 'Java [0-9]%'" | Select -ExcludeProperty Version
        return $returnValue
    }
    
    }
    
    foreach ($server in $listServer) {
        $job = start-job -InitializationScript $JavaBlock -ScriptBlock { checkServer $args } -argumentList $hostname
        $jobList += $job
        while (($jobList | where { $_.state -eq "Running" }).count -ge 30) { start-sleep -s 1 }
    }
    
    while (($jobList | | where { $_.state -eq "Running" }).count -ge 1) { start-sleep -ms 500 }
    

    The two while statements control the job flow. The one within the foreach statement throttles the jobs so that only 30 are running at once. The last just waits for all jobs to complete before finishing off.

    To gather your results, you can use this:

    $jobList | % { $jobResults = Receive-Job $_; write-host $jobResults.result }
    

    The Job object has other properties that might be worth exploring as well.

提交回复
热议问题