2017-05-08 112 views
0

我有一个PowerShell脚本来禁用Office 365中的邮件转发使用CSV文件。我想将所有错误都捕捉到外部的Txt文件中。 这是我的代码:Powershell尝试将写入错误捕获到外部txt文件

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

但它没有发现错误。

是否有任何指令来捕获外部文件的错误?

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

+2

'Write-Host'绕过管道。如果您必须使用'Out-Default',或者只是将字符串输入到Out-File' cmdlet。如果'Set-Mailbox'没有抛出错误,则需要更深入地调查另外一个问题。 –

+1

“Try/Catch”块仅在终止错误时起作用,因此如果该cmdlet抛出错误,但仅仅移动此错误将不起作用。您可能需要将'-ErrorAction Stop'添加到您的'Set-Mailbox' cmdlet。另外,正如Jeff Zeitlin所说,'Write-Host' cmdlet并没有把事情弄糟。在你的'Catch'块添加一个新行,将信息输出到你的文本文件中。 – TheMadTechnician

+0

我已经删除了写主机,仍然无法正常工作 – ysfibm

回答

1

从杰夫·蔡特林的和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 
    } 
} 
+0

我试过了代码,但仍然不起作用 – ysfibm

+0

以何种方式“仍然无法工作?” – lit

0

试试这个:

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

的Exchange Online(又名O365)不接受你的catch语句抛出的错误上班。我们不得不设置

$global:ErrorActionPreference=Stop 

获得错误对象返回

注:我们实现了这个用在功能

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

开始以下,并在年底恢复设置函数使用

$global:ErrorActionPreference=$saved