2012-01-01 105 views
15

我試着封閉在一個if語句下面,所以如果這個成功,我可以執行其他命令:檢查命令已成功運行

Get-WmiObject -Class Win32_Share -ComputerName $Server.name -Credential $credentials -Filter "Description='Default share'" | Foreach-Object { 
     $Localdrives += $_.Path 

,但我無法弄清楚如何做到這一點。我甚至嘗試創建一個函數,但我無法弄清楚如何檢查函數是否已成功完成。

回答

10

你可以試試:

$res = get-WmiObject -Class Win32_Share -Filter "Description='Default share'" 
if ($res -ne $null) 
{ 
    foreach ($drv in $res) 
    { 
    $Localdrives += $drv.Path 
    } 
} 
else 
{ 
    # your error 
} 
+0

現在爲什麼我沒有想到這一點!非常感謝:) – Sune 2012-01-01 15:48:28

36

嘗試$?自動變量:

$share = Get-WmiObject -Class Win32_Share -ComputerName $Server.name -Credential $credentials -Filter "Description='Default share'" 

if($?) 
{ 
    "command succeeded" 
    $share | Foreach-Object {...} 
} 
else 
{ 
    "command failed" 
} 

about_Automatic_Variables

$? 
    Contains the execution status of the last operation. It contains 
TRUE if the last operation succeeded and FALSE if it failed. 
... 

$LastExitCode 
    Contains the exit code of the last Windows-based program that was run. 
+1

這次我選擇了第一個解決方案,但這絕對是一個很好的方法。再次感謝謝謝:) – Sune 2012-01-01 15:49:03

+0

對不起謝:測試 'get-WmiObject-Class Win32_Share -Filter「Description ='glurp'」',但在這種情況下$?是真實的,並沒有與這個描述分享。 – JPBlanc 2012-01-01 18:10:32

+5

該命令沒有返回錯誤,所以$?被設置爲$ true。這與dir * .NoSucheExtension相同,結果是什麼也不認爲是錯誤。如果要測試命令是否返回任何結果,請使用@ JPBlanc的解決方案。 – 2012-01-01 20:10:24