我有一个循环用户列表的脚本(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
}
我想:
我一直在考虑做if(!cmdlettorun) { write-host "Error!" }
但是我认为必须有更好的方法。
我应该如何以适当的方式进行错误处理,以便最大限度地减少显示的输出但仍然可以让我看到它?如果需要的话?
答案 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