Learn about Windows PowerShell
Hey, Scripting Guy! I’m trying to determine the IP address on a computer, but I keep getting a Type Mismatch error. Do you know why? -- AQ, Jacksonville, FL
Hey, AQ. As a matter of fact, we do know why you’re getting a Type Mismatch error, and it’s a common problem when working with the WMI class Win32_NetworkAdapterConfiguration. The line in your script that’s causing the problem most likely looks something like this:
Wscript.Echo "IP Address: " & objItem.IPAddress
So what’s the problem? Well, the IPAddress property is actually stored as an array; that’s because it’s possible for multiple IP addresses to be assigned to a single network adapter. You’re treating IPAddress as though it was a string or numeric variable and it’s not; an array is a totally different datatype. Hence the Type Mismatch error. This is the same kind of error you get with this script, which tries to multiply dog times cat:
A = "dog"
B = "cat"
C = A * B
So now that we know the problem, what’s the solution? It’s actually pretty easy: you just need to loop through the IPAddress array and echo all the values found there. Admittedly, most of the time there will only be one IP address per network adapter, but that doesn’t matter: whether there’s one IP address, 100 IP addresses, or even 0 IP addresses you still need to use a For Each loop to iterate all the items in the array. A simplified version of your script would thus look like this:
strComputer = "."
Set objWMIService = GetObject _
("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery _
("Select * From Win32_NetworkAdapterConfiguration " & _
"Where IPEnabled = True")
For Each objItem in colItems
Wscript.Echo "Caption: " & objItem.Caption
For Each objAddress in objItem.IPAddress
Wscript.Echo "IP Address: " & objAddress
Bonus answer to a question you didn’t even ask: So how did we know that IPAddress is stored as an array? Well, the Type Mismatch error message gave us a pretty good clue, and then we verified that by opening up Wbemtest and locating the Win32_NetworkAdapterConfiguration class. As you can see from the following screenshot, IP address is, indeed, stored as an array: