Search code examples
powershellforeachwmicinvoke-command

Two Invoke-Command at the same time


I'm using this PowerShell script to resume Bitlocker on every active device:

Get-Content "clients.txt" | ForEach-Object {
    if (Test-Connection $_ -Count 1 -ErrorAction 0 -Quiet) {
        Invoke-Command -ComputerName $_ -ScriptBlock {
            Resume-BitLocker -MountPoint "C:"
        }
    } else {
        Write-Host "$_ is OFFLINE" -ForegroundColor Red
    }
}

But I also want to trigger a hardware inventory via Invoke-WMIMethod on every active device with this command:

Invoke-WMIMethod -ComputerName $Server -Namespace root\ccm -Class SMS_CLIENT -Name TriggerSchedule "{00000000-0000-0000-0000-000000000001}"

I was able to script the first part but it isn't that well to built in the second command.


Solution

  • you are drifting a bit in the wrong direction. When using Invoke-Command, it processes the scriptblock, against 32 computers simultaneously (in parallel)!

    If you are processing computers with foreach, it would handle them sequentially, which would be much slower. Same is valid when using *WMI cmdlets. Always try to replace them with the corresponding CIM cmdlets, as the same logic applies - computers are being processed in parallel.

    Consider something like:

    $ComputerList = Get-Content -Path Clients.txt
    Invoke-Command -ComputerName $ComputerList -ErrorAction SilentlyContinue -ScriptBlock {
        Resume-BitLocker -MountPoint "C:"
        #Add second command
        #add third command and so on
    }
    

    I am not sure, what would be the alternative command to Invoke-WMIMethod, when executing locally. Maybe Set-WMIInstance, but I am only speculating! Then if you would like to add second command for execution, just add it into the scriptblock of Invoke-Command.