Search code examples
powershellerror-handlingpipelineerror-logging

Handling error through the pipeline for logging


I was wondering if someone would be able to give me some tips on handling non terminating errors through the pipeline? Here is an example of what i would like to do.

Get-ADUser -Filter {Enabled = 'False'} -Properties Modified | Where Modified -LT (Get-Date).AddDays(-30) | Remove-ADUser -Confirm:$false

Basically find all users that are disabled where the last modified time stamp is less than 30 days ago and delete them. So what i'm looking for is how to handle and error if one where to occur so that it could be logged

I thought of using try catch, but if an error occurs then the entire command stops. I want it to be a non terminating error, so that it will continue to process all the users that it find, but then have a way to see if there where any error so that i can log them

Any suggestions?


Solution

  • You can use -ErrorVariable without a Try-Catch construct and even without -ErrorAction. So, for example, you could do this :

    Get-ADUser -Filter {Enabled = 'False'} -Properties Modified -ErrorVariable Get-ADuserErr |`
    Where Modified -LT (Get-Date).AddDays(-30) -ErrorVariable Where-ObjectErr |`
    Remove-ADUser -Confirm:$false -ErrorVariable Remove-ADuserErr
    If ($Get-ADuserErr) {
    Write-Output $Get-ADuserErr }
    If ($Where-ObjectErr) {
    Write-Output $Where-ObjectErr }
    If ($Remove-ADuserErr) {
    Write-Output $Remove-ADuserErr }
    

    That way you have a different variable to store the error of each command and you get the default error handling behaviour (from $ErrorActionPreference , which is "Continue" by default).

    Also, your error variables ($Get-ADuserErr, $Remove-ADuserErr, etc...) are objects which can be piped to Out-File to log the errors into a file.

    Even nicer, these error variables are object of the type "ErrorRecord" which have a number a properties like : TargetObject, Exception, InvocationInfo, fullyQualifiedErrorID, etc... So you can further manipulate you error variables objects to log exactly what you want.