2016-12-09 74 views
2

當檢索一臺計算機的操作系統,我得到了不同的結果,這取決於我是否如果使用的語句或開關:powerwshell IF VS交換機

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

結果=找到

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

結果=未找到

這是爲什麼?

回答

7

這不是ifswitch這是不同的;這是運營商正在使用。在您的if中,您使用的是-match,但switch默認使用的是-eq

通過使用-match您正在執行正則表達式匹配,它將在源字符串中的任意位置找到該字符串。 -eq不會。它們都應該不區分大小寫。

可以修改switch使用正則表達式或通配符匹配:

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

或:

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

另外,找出爲什麼你的字符串是不完全匹配,改變你的文字。你走哪條路取決於你的情況。

如果你不打算使用正則表達式,我會小心的正則表達式匹配,因爲它可能很容易無意中使用特殊字符或無效的正則表達式。

+0

謝謝。它確實看起來好像在返回的字符串後面有一個空格,我發現它是: '「'+(Get-WmiObject -ComputerName DT-04 Win32_OperatingSystem).Caption.trim()+'''' 感謝您的幫助! – cswalker

+2

正確和非常好的解釋答案應該通過檢查它而得到尊重。 – LotPings