检查命令已成功运行

问题描述:

我试着封闭在一个if语句下面,所以如果这个成功,我可以执行其他命令:检查命令已成功运行

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

,但我无法弄清楚如何做到这一点。我甚至尝试创建一个函数,但我无法弄清楚如何检查函数是否已成功完成。

你可以试试:

$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

尝试$?自动变量:

$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