Powershell 尝试捕获写入错误到外部 txt 文件

Powershell Try catch write errors to an external txt file

我有一个 PowerShell 脚本可以使用 CSV 文件在 Office 365 中禁用电子邮件转发。我想将所有错误捕获到外部 Txt 文件中。 这是我的代码:

$Groups |
ForEach-Object {
    $PrimarySmtpAddress = $_.PrimarySmtpAddress
    try {
        # disable Mail forwarding
        Set-Mailbox -Identity $PrimarySmtpAddress -ForwardingSmtpAddress $Null 
    }
    Catch {
        $PrimarySmtpAddress  | Out-File $logfile -Append
    }
}

但它不会捕获错误。

是否有将错误捕获到外部文件的说明?

任何解决方案都会有所帮助。

根据 Jeff Zeitlin 和 TheMadTechnician 的评论,在线评论中指出的更改:

$Groups | ForEach-Object {
    $PrimarySmtpAddress = $_.PrimarySmtpAddress
    Try {
        # disable Mail forwarding
        #Added ErrorAction Stop to cause errors to be terminating
        Set-Mailbox -Identity $PrimarySmtpAddress -ForwardingSmtpAddress $Null -ErrorAction Stop
    }
    Catch {
        #Removed Write-Host as Write-Host writes to the host, not down the pipeline, Write-Output would also work
        "$PrimarySmtpAddress" | Out-File $logfile -Append
    }
 }

试试这个:

    $ErrorMessage = $_.Exception.Message
    #or $ErrorMessage= $Error[0].Exception.Message
    if($ErrorMessage -ne $null) {
        ... Your custom code
    }

Exchange Online (a.k.a O365) 不接受抛出的错误以使您的 catch 语句起作用。我们不得不设置

$global:ErrorActionPreference=Stop

获取错误对象到return

注意:我们在函数的开头使用以下内容实现了这一点

$saved=$global:ErrorActionPreference
$global:ErrorActionPreference=Stop

并使用

恢复函数末尾的设置
$global:ErrorActionPreference=$saved