Hey, Scripting Guy! Weekend Scripter: How Can I Use WMI to Detect Laptops?

ScriptingGuy1

Bookmark and Share

Microsoft Scripting Guy Ed Wilson here. With the 2010 Scripting Games over, I have a bit of extra time on the weekends. I was catching up on reading some of my favorite blogs, such as the WMI team blog, when I ran across a post that reminded me of a question I used to be asked when I was teaching my WMI class. I was often asked about detecting laptops. The WMI class that immediately springs to mind is Win32_SystemEnclosure. The problem is there are several potential values that might be reported for the chasisTypes property. The values are documented on MSDN. One of my students suggested checking for the presence of a battery. This is also a good idea and can be incorporated easily into a script by using the Win32_Battery WMI class.

The problem with both of these approaches is that at times, they simply do not work. WMI is dependent upon hardware vendors for certain things, and at times WMI support is lacking. Sometimes, using Win32_SystemEnclosure will work, and at other times Win32_Battery will work. Therefore, it is actually a good idea to use both approaches. This is easily accomplished in Windows PowerShell and is illustrated here in the Get-Laptop.ps1 script.

Get-Laptop.ps1

Function Get-Laptop
{
 Param(
 [string]$computer = “localhost”
 )
 $isLaptop = $false
 if(Get-WmiObject -Class win32_systemenclosure -ComputerName $computer |
    Where-Object { $_.chassistypes -eq 9 -or $_.chassistypes -eq 10 `
    -or $_.chassistypes -eq 14})
   { $isLaptop = $true }
 if(Get-WmiObject -Class win32_battery -ComputerName $computer)
   { $isLaptop = $true }
 $isLaptop
} # end function Get-Laptop

# *** entry point to script ***

If(get-Laptop) { “it’s a laptop” }
else { “it’s not a laptop”}

The Get-Laptop function accepts the name of a computer for input, but it also runs locally by default. A variable, $isLaptop, is created and set to false. If either of the two WMI queries returns instances, the variable is set to true.

When the script is run, it looks for true or false to be returned from the function. If the function returns true, the script displays, “its a laptop.” The results from running the script on my desktop are seen in the following image.

Image of results of Ed running script on his desktop computer

 

If you want to know exactly what we will be looking at tomorrow, follow us on Twitter or Facebook. If you have any questions, send e-mail to us at scripter@microsoft.com or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

 

Ed Wilson and Craig Liebendorfer, Scripting Guys

 

0 comments

Discussion is closed.

Feedback usabilla icon