2012-03-27 28 views
1

我有過的用戶列表(Sam帳戶名)循環的腳本:錯誤處理,並儘量減少腳本輸出到最終用戶

# Read usersfile to variable 
$users = get-content ("users.txt") 

# Get current time 
$now = $(get-date -uformat "%H:%M %d/%m/%Y") 

# Loop through list of users 
foreach($user in $users) { 

    # Disable user 
    Disable-QADUser $user 

    # Set informative description 
    Set-QADuser $user -Description "Disabled $now" 

    # Delete all groupmemberships except "domain users" 
    Get-QADGroup -Containsmember $user | where-object { $_.name -ne 'domain users'} | Remove-QADGroupmember 

    # Move to "disabled users" group 
    move-QADObject $user -NewParentContainer 'contosoc.com/Disabled users' 

    # Hide from addresslist 
    Set-Mailbox -identity $user -HiddenFromAddressListsEnabled $true 

    # Moving mailbox to disabled users database 
    Move-Mailbox -Identity $user -TargetDatabase "myserver\mydb" -BadItemLimit 50 -Confirm:$False 
} 

我想:從

  • 禁止輸出不同的cmdlet,只顯示「$ user is OK!」如果一切正常並將日誌成功記錄到logfile.txt
  • 顯示「Error!」以及如果不行就失敗的命令。並將完整的錯誤消息輸出到單獨的日誌文件中。

我一直在想做一個if(!cmdlettorun) { write-host "Error!" }但我在想,一定有更好的辦法。

我應該如何以正確的方式進行錯誤處理,以便儘量減少顯示的輸出,但仍然讓我看到它,如果可取?

回答

1

爲了抑制cmlet輸出可通過管道傳遞out-null或先於命令:

[void](.. your cmdlets..) 

在這個最小碼爲您的目標的一個好方法是使用像托盤追趕終於代碼:

$a = $ErrorActionPreference 
$ErrorActionPreference = "SilentlyContinue" 

foreach($user in $users) { 

try 
{ 
... yours code ... 
$JobStatus = "OK" 
} 
catch [exception] 
{ 
    $("Error catched: " + $_.Exception.GetType().FullName) | out-file c:\file.log 
    $("Error catched: " + $_.Exception.Message) | out-file c:\file.log -append 

    $JobStatus = "not OK" 
    continue; 
} 
finally 
{ 
    write-host "$user is $JobStatus!" 
} 
    $ErrorActionPreference = $a 
} 

對於一些提示使用try-catch-finally閱讀here

+1

最後會一直執行這樣'「$用戶是OK!」'將始終打印......即使如果有例外! – 2012-03-27 07:43:21

+0

@AndyArismendi |哎呀!接得好!編輯我的答案.. – 2012-03-27 07:45:03

+0

謝謝基督教徒。但是,我將如何輸出錯誤消息到一個文件?如果我試圖通過out-file管道,我會得到「空管道不允許」。 – Sune 2012-03-27 08:10:25