2017-05-08 3 views
0

CSV 파일을 사용하여 Office 365에서 전자 메일 전달을 사용하지 않도록 설정하는 PowerShell 스크립트가 있습니다. 모든 오류를 외부 Txt 파일에 catch하고 싶습니다. 다음은 내 코드입니다 :Powershell 외부 txt 파일에 쓰기 오류를 시도하십시오.

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

하지만 오류를 포착하지 않습니다.

외부 파일에 오류를 catch하라는 지시가 있습니까?

모든 해결책이 유용 할 것입니다. 이 시도

$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 
    } 
} 
+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

은 변화가 인라인 주석에서 언급

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

코드를 시도했지만 여전히 작동하지 않습니다. – ysfibm

+0

"여전히 작동하지 않습니다." – lit

0

을 :

제프 Zeitlin의 및 TheMadTechnician의 의견에서
0

을 Exchange Online (일명 O365) 당신의 catch 문에 대한 던져 오류를 준수하지 않습니다 일하다. 우리는이 기능

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

의 시작 부분에 다음과 같은 사용하여 구현의 끝에서 설정을 복귀 : 우리는

주를 반환하는 오류 개체를 가져

$global:ErrorActionPreference=Stop 

를 설정해야했다 함수를 사용하여

$global:ErrorActionPreference=$saved