2

As the title says, how could someone speed up the execution of this tiny script? Am I using the New-CimSession that right way anyway?

$computers = Get-ADComputer -SearchBase "OU=W2012,OU=Servers,DC=contoso,DC=com" -Filter *

foreach ($computer in $computers) 
{
    Get-ScheduledTask -TaskName "SomeTask" -CimSession (New-CimSession -ComputerName $computer.Name) 
}
Matthias Güntert
  • 2,438
  • 12
  • 39
  • 59

2 Answers2

1

Look into using background jobs for the Get-ScheduledTask cmdlet. This will run the command asynchronously.

foreach ($computer in $computers) {
    start-job -scriptblock {
        #Parse Args
        $CompName = $args[0]
        $TaskName = $args[1]

        Get-ScheduledTask -TaskName $TaskName -CimSession (New-CimSession -ComputerName $CompName)
    } -name( "SchedTask_$($computer)" ) -ArgumentList $computer, "Task Name"
}

After which you need to wait until your jobs are in a "Completed" state and then use Receive-Job to get the output. Geek School: Learn How to Use Jobs in PowerShell

Bin
  • 864
  • 5
  • 15
-1

Just do:

$computers = Get-ADComputer -SearchBase "OU=W2012,OU=Servers,DC=contoso,DC=com" -Filter *
$sessions = New-CimSession -ComputerName $computers.Name

Get-ScheduledTask -TaskName "SomeTask" -CimSession $sessions 
HopelessN00b
  • 53,795
  • 33
  • 135
  • 209