错误处理并最小化脚本输出到最终用户

时间:2012-03-27 07:12:23

标签: powershell error-handling

我有一个循环用户列表的脚本(samaccountname):

# 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
  • 显示“错误!”以及如果不正确则失败的命令。并将完整的错误消息输出到单独的日志文件。

我一直在考虑做if(!cmdlettorun) { write-host "Error!" }但是我认为必须有更好的方法。

我应该如何以适当的方式进行错误处理,以便最大限度地减少显示的输出但仍然可以让我看到它?如果需要的话?

1 个答案:

答案 0 :(得分:1)

为了抑制cmlet输出,您可以通过以下方式输入out-null或在命令前面输入:

[void](.. your cmdlets..)

实现目标的一个好方法是使用像这样最小化的代码中的tray-catch-finally代码:

$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