cswalker
cswalker

Reputation: 21

powerwshell IF vs Switch

When retrieving the OS of a computer, I get a different result depending on whether i'm using an if statement or a switch:

if (((Get-WmiObject -ComputerName DT-04 Win32_OperatingSystem).Caption.ToString()) -match "Microsoft Windows 7 Professional") { "Found" } Else { "Not found" } 

Result = Found

switch ((Get-WmiObject -ComputerName DT-04 Win32_OperatingSystem).Caption.ToString()) { "Microsoft Windows 7 Professional" { "Found" } Default { "Not Found" } }

Result = Not Found

Why is this the case?

Upvotes: 2

Views: 72

Answers (1)

briantist
briantist

Reputation: 47832

It's not if vs. switch that's making this different; it's the operators being used. In your if you're using -match but switch by default is using -eq.

By using -match you're doing a regular expression match, which will find that string anywhere in the source string. -eq will not. They should both be case insensitive.

You can modify switch to use regex or wildcard matching:

switch -regex ((Get-WmiObject -ComputerName DT-04 Win32_OperatingSystem).Caption.ToString()) 
{ 
    "Microsoft Windows 7 Professional" { "Found" } 
    Default { "Not Found" } 
}

or:

switch -wildcard ((Get-WmiObject -ComputerName DT-04 Win32_OperatingSystem).Caption.ToString()) 
{ 
    "*Microsoft Windows 7 Professional*" { "Found" } 
    Default { "Not Found" } 
}

Alternatively, find out why your string is not an exact match and change your literal. Which way you go will depend on your situation.

I'd be careful about the regex matching if you're not intending to use regex because it could be easy to inadvertently use special characters or invalidate your regex.

Upvotes: 7

Related Questions