检查命令是否已成功运行

Sun*_*une 20 powershell if-statement

我已经尝试将以下内容包含在if语句中,这样如果成功,我可以执行另一个命令:

Get-WmiObject -Class Win32_Share -ComputerName $Server.name -Credential $credentials -Filter "Description='Default share'" | Foreach-Object {
        $Localdrives += $_.Path
Run Code Online (Sandbox Code Playgroud)

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

Sha*_*evy 58

试试$?自动变量:

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

if($?)
{
   "command succeeded"
   $share | Foreach-Object {...}
}
else
{
   "command failed"
}
Run Code Online (Sandbox Code Playgroud)

来自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.
Run Code Online (Sandbox Code Playgroud)

  • 该命令没有返回错误所以$?设置为$ true.这与:dir*.NoSucheExtension相同,结果为空,不被视为错误.如果要测试该命令是否返回任何结果,请使用@ JPBlanc的解决方案. (5认同)
  • 这次我选择了第一个解决方案,但这绝对是一个很好的方法。再次感谢谢伊:) (3认同)

JPB*_*anc 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
}
Run Code Online (Sandbox Code Playgroud)