Search code examples
powershelltry-catch

Try, catch : doing something if the TRY completed successfully


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:)


Solution

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