问题
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!
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:)
回答1:
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
}
回答2:
One important thing to keep in mind: if for some reason disabling the user didn't work, your catch block WILL NOT invoke since the error is not a terminating error. To change the type of the error to terminating error, use the ErrorAction parameter:
Set-QADuser $user -Description "Disabled $now" -ErrorAction Stop | ...
来源:https://stackoverflow.com/questions/9905445/try-catch-doing-something-if-the-try-completed-successfully