Powershell – Waiting for WMI Queries

One of the strategies for creating responsive graphical powershell forms is to offload long processes to a new job, and then have a timer check for the job to complete and grab the result. I’ve been working on a large script with plenty of WMI queries, however I didn’t want to write code for every new query. I also wanted the data back in a hash table to make it easier to get into a datagridview.

$WMIQuerySB = {
Param ([string]$strComputer,[string]$strWMIQuery,[string]$2ndArg)
			$HashTableCollection = @{ }
			$SBWMIQuery = [Scriptblock]::Create($strWMIQuery)
			#Get WMI query
			$WMICollection = $SBWMIQuery.Invoke()
			$i = 0
			ForEach ($WMIObject in $WMICollection)
				if (!($HashTableCollection.ContainsKey($i)))
					$HashTableCollection.Add($i, $WMIObject)
	return $HashTableCollection

$strComputer = "localhost"
$2ndArg = $AppID  #You need to know the AppID beforehand

#You can use any command to get the wmi object, so long as the command returns a wmi object.
$WMIQuery = {
		gwmi -Namespace root\ccm\clientsdk -Query "Select * From CCM_Application" -ComputerName $strComputer | Where-Object -Property ID -eq $2ndArg | ForEach{ $_.PsBase.Get()

Start-Job -Name $Name -ScriptBlock $WMIQuerySB -ArgumentList ($strComputer,$WMIQuery,$2ndArg)

Note: The parameters in the $WMIQuerySB script block are optional, depending on what variables your wmi query requires. I’ve included $strComputer for the computer you want to run the WMI query against, $strWMIQuery for the wmi query, and $2ndArg as an additional parameter if you want add a filter to your WMI query. This provides a method to pass variables to your wmi query, and you can add more if you want.

For information on how to get the Hashtable from the powershell job, see this great blog post:


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s