我正在遍历一个samaccountnames列表并执行几个操作:
# Disabling user
try {
Disable-QADUser $user | Out-Null
} catch [exception] {
"Disable-QADuser: " + $($_.Exception.Message) | out-file $logfile -append
write-host " - Error disabling useraccount." -fore yellow
}
# Set informative description
try {
Set-QADuser $user -Description "Disabled $now" | Out-Null
} catch [exception] {
"Set-QADuser: " + $($_.Exception.Message)| out-file $logfile -append
write-host " - Error setting informative description in AD." -fore yellow
}
但如果命令成功完成,如何输出内容?像
这样的东西write-host "User $user disabled"
"User $user disabled" | out-file $logfile -append
非常感谢所有帮助/指针!
修改
我注意到我可以使用tee-object
将输出发送到文件以及控制台。这样我就不必去输出“tee”输出:)
答案 0 :(得分:5)
可能在这里表现出我的无知(我对power-shell一无所知,抱歉 - 不要投票给我!)。但如果它像java一样,你只需将它放在你想要执行的行下面:
try {
Set-QADuser $user -Description "Disabled $now" | Out-Null
write-host "User $user disabled"
"User $user disabled" | out-file $logfile -append
} catch [exception] {
"Set-QADuser: " + $($_.Exception.Message)| out-file $logfile -append
write-host " - Error setting informative description in AD." -fore yellow
}
答案 1 :(得分:1)
要记住的一件重要事情:如果由于某种原因禁用用户不起作用,则不会调用catch块,因为错误不是终止错误。要将错误类型更改为终止错误,请使用ErrorAction参数:
Set-QADuser $user -Description "Disabled $now" -ErrorAction Stop | ...