如何检查一个PowerShell命令是否成功?

是否有可能检查一个PowerShell命令是否成功?

例:

Set-CASMailbox -Identity:blocks.5 -OWAMailboxPolicy“DoNotExists”

造成了这个错误:

Outlook Web App mailbox policy "DoNotExists" wasn't found. Make sure you typed the policy name correctly. + CategoryInfo : NotSpecified: (0:Int32) [Set-CASMailbox], ManagementObjectNotFoundException + FullyQualifiedErrorId : 9C5D12D1,Microsoft.Exchange.Management.RecipientTasks.SetCASMailbox 

我认为应该可以获取FullyQualifiedErrorId,所以我尝试了以下内容:

$ test = Set-CASMailbox -Identity:blocks.5 -OWAMailboxPolicy“DoNotExists”

但是看起来错误没有被转移到testingvariables中。

那么执行如下操作的正确方法是什么?

 $test = Set-CASMailbox -Identity:blocks.5 -OWAMailboxPolicy "DoNotExists" if ($test -eq "error") { Write-Host "The Set-CASMailbox command failed" } else { Write-Host "The Set-CASMailbox command completed correctly" } 

阅读Set-CASMailbox参考 :

  • OwaMailboxPolicy参数:

OwaMailboxPolicy参数指定邮箱的Web邮箱策略上的Outlook。 您可以使用唯一标识Web邮箱策略上的Outlook的任何值。 例如:

  • 名称
  • 可分辨名称(DN)
  • GUID

Web邮箱策略上的默认Outlook的名称是“默认”。

  • Cmdletinput和输出types 。 如果输出types字段为空,则该cmdlet不会返回数据 (这是Set-CASMailbox情况)。

请阅读about_CommonParameters ( 可以与任何cmdlet一起使用的参数 ),应用ErrorVariableErrorAction

ErrorVariable

 Set-CASMailbox -Identity:blocks.5 -OWAMailboxPolicy "DoNotExists" -ErrorVariable test if ($test.Count -neq 0) ### $test.GetType() is always ArrayList { Write-Host "The Set-CASMailbox command failed: $test" } else { Write-Host "The Set-CASMailbox command completed correctly" } 

ErrorActionTry,Catch,Finally (阅读about_Try_Catch_Finally 如何使用Try,Catch和Finally块来处理终止错误 ):

 try { Set-CASMailbox -Identity:blocks.5 -OWAMailboxPolicy "DoNotExists" -ErrorAction Stop ### set action preference to force terminating error: ↑↑↑↑↑↑↑↑↑↑↑↑ ↑↑↑↑ Write-Host "The Set-CASMailbox command completed correctly" } catch { Write-Host "The Set-CASMailbox command failed: $($error[0])" -ForegroundColor Red } 

无论如何,阅读写主机被认为是有害的