How do I add multi-threading?

2019-03-20 09:30发布

问题:

Is there a way of getting the below to run in parallel (multi-threading)? I have about 200 servers that need to run and was wondering if there is a way of checking say 10 servers at once rather then one at a time...WMI is very slow in checking this one at a time.

clear
Write-Host "Script to Check if Server is Alive and Simple WMI Check"

$servers = Get-Content -Path c:\Temp\Servers.txt

foreach($server in $servers)
{
    if (Test-Connection -ComputerName $server -Quiet)
    {
    $wmi = (Get-WmiObject -Class Win32_ComputerSystem -ComputerName $server).Name

    Write-Host "$server responds: WMI reports the name is: $wmi"
    }

    else
    {
    Write-Host "***$server ERROR - Not responding***"
    }
}

回答1:

Use powershell jobs:

$scriptblock = {
    Param($server)
    IF (Test-Connection $server -Quiet){
        $wmi = (gwmi win32_computersystem -ComputerName $server).Name
        Write-Host "***$server responds: WMI reports the name is: $wmi"
    } ELSE { Write-Host "***$server ERROR -Not responding***" }
}
$servers | % {Start-Job -Scriptblock $scriptblock -ArgumentList $_ | Out-Null}
Get-Job | Wait-Job | Receive-Job