Jump to page sections
- Changing the WMI Timeout Value for a Series of WMI Queries
- Source Code For An Example Script With A WMI Timeout
- Example Use
- Example Output
- Screenshot of Example Output
- A Couple of Examples Where We Filter Away Errors and Redirect to a File
Changing the WMI Timeout Value for a Series of WMI Queries
To change/tweak the WMI timeout value, you can instantiate a WMI or WMI searcher object and set its timeout property, which is a time span object. In this informational top example, it's done through the PSBase member set. Notice the empty string after the [wmi] type accelerator in the example directly below. The WMI timeout is only changed for that specific object instance, so this is basically useless other than for the sake of enlightenment.
The example further down uses a [WmiSearcher] object and sets its properties. This top example is for informational purposes only. Look at the code below to see the real deal immediately.Now the bad news: During testing I discovered that the clients that "get stuck" still get stuck... And the timeout appears only to be in effect if WMI is working properly on the target computer. It appears to be limiting the time an actual query takes, not when to abort the attempt. Now that makes it a lot less useful; I will have to dig deeper to see if this broken behavior is at all remediable. Note made 2022-01-25: Runspaces allow you to set a timeout, as do PowerShell jobs. See Get-Help Start-Job.
Also consider checking out the PowerShell Get-WmiObject Wrapper script here. It's pretty darn useful. It uses runspaces to handle the timeouts.PS E:\> $wmi = [wmi]'' PS E:\> $wmi.PSBase.Options.Timeout = '0:0:5'
Here "0:0:5" is cast to a time span value, which in this case is equivalent to 5 seconds (hours:minutes:seconds). You can look at the timeout property you just set like this:
PS E:\> $wmi.PSBase.Options.Timeout Days : 0 Hours : 0 Minutes : 0 Seconds : 5 Milliseconds : 0 Ticks : 50000000 TotalDays : 5,78703703703704E-05 TotalHours : 0,00138888888888889 TotalMinutes : 0,0833333333333333 TotalSeconds : 5 TotalMilliseconds : 5000
To inspect the various properties, use:
$wmi.PSBase | Get-Member
... and
$wmi.PSBase.Options | Get-Member
Source Code For An Example Script With A WMI Timeout
# Utility function making lists "less quoty" function ql { $args } # A list of computers to process. $Computers = ql win7esxi ubuntu64esxi silverstone winxpesxi 2008r2esxi localhost # The purpose here is to have clean output to the console (or redirected to a file). $Computers | ForEach-Object { # This is needed for the error handling in the catch block where $_ gets # set to the last error rather than the computer name. $Computer = $_ # Since certain WMI errors are terminating, we need a try/catch statement. try { # Here we specify the WMI query $Searcher = [WmiSearcher]'SELECT * FROM Win32_ComputerSystem' # This is where we set the timeout to 5 seconds. $Searcher.Options.TimeOut = "0:0:5" # Create necessary objects, specify a scope and namespace for the remote computer (or localhost or '.'), # then set the scope on the WMISearcher object, which is usually "\\computername\root\cimv2". $ConnectionOptions = New-Object Management.ConnectionOptions $ManagementScope = New-Object Management.ManagementScope("\\${Computer}\root\cimv2", $ConnectionOptions) $Searcher.Scope = $ManagementScope # Perform the query and retrieve the desired property, and expand it to a # string with Select -ExpandProperty. $MemSize = $Searcher.Get() | Select-Object -ExpandProperty TotalPhysicalMemory # Use this check for if there's a non-terminating error. if ($?) { $MemSizeGB = ($MemSize/1GB).ToString('N') Write-Output "${computer}: $MemSizeGB" } # If a non-terminating error occurs, we get here, but I think all errors are terminating with $searcher.Get() ... else { Write-Output "${Computer}: Error: $($Error[0])" } } # If WMI has a terminating error, we get here. catch { Write-Output "${Computer}: Error (terminating): $($Error[0])" } }
Example Use
You can use PowerShell jobs, which can be combined with a lowered, or increased, WMI timeout value. You can also check out another non-generic example using jobs, in this article about getting computer models in a domain.
Note made on 2022-01-25: This article is ... "weird". I'm not 100 % sure my test environment was representative when I was researching this. The article gets some minor traffic, which tells me it helps some people with something. For a way to set a thread timeout using efficient runspaces, see this article. These runspaces are compatible with PowerShell version 2 and up. With PowerShell 7 / PowerShell Core came Foreach-Object -Parallel, which you may want to research.
Example Output
PS C:\prog\Powershell> .\Wmi-Timeout-Example-New.ps1 win7esxi: 2.00 ubuntu64esxi: Error (terminating): Exception calling "Get" with "0" argument(s): "The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)" silverstone: Error (terminating): Exception calling "Get" with "0" argument(s): "Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))" winxpesxi: 0.50 2008r2esxi: 2.00 localhost: 2.00
Screenshot of Example Output
A Couple of Examples Where We Filter Away Errors and Redirect to a File
PS C:\prog\Powershell> .\Wmi-Timeout-Example-New.ps1 | Select-String -NotMatch 'error' > memsize.txt PS C:\prog\Powershell> type .\memsize.txt win7esxi: 2.00 winxpesxi: 0.50 2008r2esxi: 2.00 localhost: 2.00
For better validation, and not excluding unwanted lines that for some reason contain the string "error", we can use a regular expression (read more about regular expressions here) for more control. This should be sufficient in most cases:
PS C:\prog\Powershell> .\Wmi-Timeout-Example-New.ps1 | Select-String -NotMatch '^[^:]+:\s*Error' > memsize.txt PS C:\prog\Powershell> type .\memsize.txt win7esxi: 2.00 winxpesxi: 0.50 2008r2esxi: 2.00 localhost: 2.00
The regular expression used above is "^[^:]+:\s*Error", which means: Start at the beginning, match one or more non-colon characters, as many as you can, match a literal colon (":"), possibly whitespace ("*" is a quantifier and indicates zero or more, always matches) and it's finally followed by the literal string "Error".
Powershell Windows WmiBlog articles in alphabetical order
A
- A Look at the KLP AksjeNorden Index Mutual Fund
- A primitive hex version of the seq gnu utility, written in perl
- Accessing the Bing Search API v5 using PowerShell
- Accessing the Google Custom Search API using PowerShell
- Active directory password expiration notification
- Aksje-, fonds- og ETF-utbytterapportgenerator for Nordnet-transaksjonslogg
- Ascii art characters powershell script
- Automatically delete old IIS logs with PowerShell
C
- Calculate and enumerate subnets with PSipcalc
- Calculate the trend for financial products based on close rates
- Check for open TCP ports using PowerShell
- Check if an AD user exists with Get-ADUser
- Check when servers were last patched with Windows Update via COM or WSUS
- Compiling or packaging an executable from perl code on windows
- Convert between Windows and Unix epoch with Python and Perl
- Convert file encoding using linux and iconv
- Convert from most encodings to utf8 with powershell
- ConvertTo-Json for PowerShell version 2
- Create cryptographically secure and pseudorandom data with PowerShell
- Crypto is here - and it is not going away
- Crypto logo analysis ftw
D
G
- Get rid of Psychology in the Stock Markets
- Get Folder Size with PowerShell, Blazingly Fast
- Get Linux disk space report in PowerShell
- Get-Weather cmdlet for PowerShell, using the OpenWeatherMap API
- Get-wmiobject wrapper
- Getting computer information using powershell
- Getting computer models in a domain using Powershell
- Getting computer names from AD using Powershell
- Getting usernames from active directory with powershell
- Gnu seq on steroids with hex support and descending ranges
- Gullpriser hos Gullbanken mot spotprisen til gull
H
- Have PowerShell trigger an action when CPU or memory usage reaches certain values
- Historical view of the SnP 500 Index since 1927, when corona is rampant in mid-March 2020
- How to check perl module version
- How to list all AD computer object properties
- Hva det innebærer at særkravet for lån til sekundærbolig bortfaller
I
L
M
P
- Parse openssl certificate date output into .NET DateTime objects
- Parse PsLoggedOn.exe Output with PowerShell
- Parse schtasks.exe Output with PowerShell
- Perl on windows
- Port scan subnets with PSnmap for PowerShell
- PowerShell Relative Strength Index (RSI) Calculator
- PowerShell .NET regex to validate IPv6 address (RFC-compliant)
- PowerShell benchmarking module built around Measure-Command
- Powershell change the wmi timeout value
- PowerShell check if file exists
- Powershell check if folder exists
- PowerShell Cmdlet for Splitting an Array
- PowerShell Executables File System Locations
- PowerShell foreach loops and ForEach-Object
- PowerShell Get-MountPointData Cmdlet
- PowerShell Java Auto-Update Script
- Powershell multi-line comments
- Powershell prompt for password convert securestring to plain text
- Powershell psexec wrapper
- PowerShell regex to accurately match IPv4 address (0-255 only)
- Powershell regular expressions
- Powershell split operator
- Powershell vs perl at text processing
- PS2CMD - embed PowerShell code in a batch file
R
- Recursively Remove Empty Folders, using PowerShell
- Remote control mom via PowerShell and TeamViewer
- Remove empty elements from an array in PowerShell
- Remove first or last n characters from a string in PowerShell
- Rename unix utility - windows port
- Renaming files using PowerShell
- Running perl one-liners and scripts from powershell
S
- Sammenlign gullpriser og sølvpriser hos norske forhandlere av edelmetall
- Self-contained batch file with perl code
- Simple Morningstar Fund Report Script
- Sort a list of computers by domain first and then name, using PowerShell
- Sort strings with numbers more humanely in PowerShell
- Sorting in ascending and descending order simultaneously in PowerShell
- Spar en slant med en optimalisert kredittkortportefølje
- Spre finansiell risiko på en skattesmart måte med flere Aksjesparekontoer
- SSH from PowerShell using the SSH.NET library
- SSH-Sessions Add-on with SCP SFTP Support
- Static Mutual Fund Portfolio the Last 2 Years Up 43 Percent
- STOXR - Currency Conversion Software - Open Exchange Rates API