Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get-WmiObject with a timeout
Function Get-WmiObjectTimeout {
<#
.SYNOPSIS
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
parameter
.PARAMETER 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.
.NOTES
Author: Ryan Leap
https://blogs.msdn.microsoft.com/dmuscett/2009/05/27/get-wmicustom-aka-get-wmiobject-with-timeout/
#>
param(
[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) {
$ConnectionOptions.set_Username($Credential.UserName)
$ConnectionOptions.set_SecurePassword($Credential.Password)
}
$EnumerationOptions = New-Object -TypeName System.Management.EnumerationOptions -ErrorAction Stop
$timeoutSeconds = New-TimeSpan -seconds $Timeout
$EnumerationOptions.set_timeout($timeoutSeconds)
$assembledPath = "\\" + $ComputerName + "\" + $Namespace
$scope = New-Object System.Management.ManagementScope $assembledPath, $ConnectionOptions -ErrorAction Stop
if ($scope) {
Try {
$scope.Connect()
$querystring = "SELECT * FROM " + $Class
$searcher = New-Object System.Management.ManagementObjectSearcher -ErrorAction Stop
$searcher.set_options($EnumerationOptions)
$searcher.Query = $querystring
$searcher.Scope = $Scope
$searcher.get()
}
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