尝试,捕获:如果TRY成功完成,做一些事情

时间:2012-03-28 10:17:07

标签: powershell try-catch

我正在遍历一个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”输出:)

2 个答案:

答案 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 | ...