Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Get-WmiObject with a timeout
Function Get-WmiObjectTimeout {
Get-WmiObject call with a timeout
.PARAMETER ComputerName
Specifies the target computer for the management operation
.PARAMETER Namespace
Specifies the WMI repository namespace where the specified WMI class is located when used with the Class
Specifies the name of a WMI class
.PARAMETER Credential
Specifies a user account that has permission to perform this action. The default is the current user.
Author: Ryan Leap
[string] $ComputerName,
[string] $Namespace = 'root\cimv2',
[string] $Class,
[System.Management.Automation.PSCredential] $Credential = [System.Management.Automation.PSCredential]::Empty,
[int] $Timeout = 15
$ConnectionOptions = New-Object -TypeName System.Management.ConnectionOptions -ErrorAction Stop
if (([System.Management.Automation.PSCredential]::Empty) -ne $Credential) {
$EnumerationOptions = New-Object -TypeName System.Management.EnumerationOptions -ErrorAction Stop
$timeoutSeconds = New-TimeSpan -seconds $Timeout
$assembledPath = "\\" + $ComputerName + "\" + $Namespace
$scope = New-Object System.Management.ManagementScope $assembledPath, $ConnectionOptions -ErrorAction Stop
if ($scope) {
Try {
$querystring = "SELECT * FROM " + $Class
$searcher = New-Object System.Management.ManagementObjectSearcher -ErrorAction Stop
$searcher.Query = $querystring
$searcher.Scope = $Scope
Catch {
Throw $_.Exception
else {
Throw "Unable to create a WMI scope object for computer [$ComputerName]. Cannot connect."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment