检查命令是否已成功运行

时间:2012-01-01 14:57:30

标签: powershell if-statement

我已尝试在if语句中包含以下内容,以便在成功时执行另一个命令:

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

但我无法弄明白该怎么做。我甚至尝试创建一个函数,但我无法弄清楚如何检查函数是否已成功完成。

4 个答案:

答案 0 :(得分:53)

试试$?自动变量:

$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 :(得分:9)

你可以尝试:

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

答案 2 :(得分:1)

在某些情况下,任何选项都是最合适的。这是另一种方法:

try {
Add-AzureADGroupMember -ObjectId XXXXXXXXXXXXXXXXXXX -RefObjectId (Get-AzureADUser -ObjectID "XXXXXXXXXXXXXX").ObjectId  -ErrorAction Stop
Write-Host "Added successfully" -ForegroundColor Green
$Count = $Null
$Count = 1
}
catch {
$Count = $Null
$Count = 0
Write-Host "Failed to add: $($error[0])"  -ForegroundColor Red
}

通过try and catch,不仅会收到失败时返回的错误消息,还为$ count变量分配了数字0。命令成功后,您的$ count值将返回1。 ,您可以使用此变量值来确定接下来会发生什么。

答案 3 :(得分:1)

或者,如果失败不返回任何标准输出,则适用于if语句:

if (! (Get-CimInstance Win32_Share -ComputerName $Server.name -Credential $credentials -Filter "Description='Default share'")) { 
  'command failed'
}

现在还有or符号“ ||”在Powershell 7中:

Get-CimInstance Win32_Share -ComputerName $Server.name -Credential $credentials -Filter "Description='Default share'" || 'command failed'