Try, catch : 如果 TRY 成功完成,则做某事 [英] Try, catch : doing something if the TRY completed successfully

查看:35
本文介绍了Try, catch : 如果 TRY 成功完成,则做某事的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遍历 samaccountnames 列表并执行几个操作:

I am looping through a list of samaccountnames and performing several actions:

# 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
} 

但是如果命令成功完成,我该如何输出?类似的东西

But how do I output something if the command completed successfully? Something like

write-host "User $user disabled"
"User $user disabled" | out-file $logfile -append

非常感谢所有帮助/指示!

All help/pointers are greatly appreciated!

编辑我注意到我可以使用 tee-object 将输出发送到文件和控制台..这样我就不必排队来tee"输出:)

EDIT I noticed that I can use tee-object to send the output to file as well as console.. This way I do not have to have to lines to "tee" the output:)

推荐答案

这可能是在暴露我的无知(我对 power-shell 一无所知,抱歉 - 不要给我投反对票!).但如果它是类似 java 的东西,你只需将它放在你试图执行的行下面:

Probably showing my ignorance here (I know nothing about power-shell, sorry - don't down vote me!). But if it's anything like java, you'd just place it underneath the line you are trying to execute:

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
} 

这篇关于Try, catch : 如果 TRY 成功完成,则做某事的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆