Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timeout Get-WMIObject cmdlet

Tags:

powershell

wmi

I run a script which performs many WMI-querys - but the cmdlet hangs if the server doesn't answer.. Is there any way I can make this (or any other cmndlet for that matter) timeout and exit if X seconds has passed?

Edit

Thanks to a tip from mjolinor the solution is to run this as -asjob and set a timeout in a while loop. But this is run from within a job already (started with Start-Job). So how do I know I am controlling the correct job?

This is my code from inside my already started job:

Get-WmiObject Win32_Service -ComputerName $server -AsJob

$Complete = Get-date

While (Get-Job -State Running){
    If ($(New-TimeSpan $Complete $(Get-Date)).totalseconds -ge 5) {
        echo "five seconds has passed, removing"
        Get-Job  | Remove-Job -Force
    }
    echo "still running"
    Start-Sleep -Seconds 3
}

PS: My jobs started with Start-Jobs are already taken care of..

like image 618
Sune Avatar asked Feb 16 '26 16:02

Sune


1 Answers

You could try the get-wmiCustom function, posted here. Wouldn't it be nice if get-wmiObject had a timeout parameter? Let's upvote this thing.

like image 177
noam Avatar answered Feb 18 '26 22:02

noam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!