Error Handling with Powershell script

Micro_Techie 116 Reputation points
2021-08-09T14:58:38.53+00:00

Dear All,

I need your little assistance with the below code, it is working fine. However, I want that each successful change and error should be recorded in a log file. IF the modification is successful then it should record a log success message & should record an error in case of a failure.

$List = Import-csv c:\new\input.csv
ForEach ($User in $List)
{
Get-ADUser -Identity $User.samaccountname | Set-ADAccountExpiration -TimeSpan (New-TimeSpan -Days 100)
}
Windows for business | Windows Client for IT Pros | Directory services | Active Directory
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

Answer accepted by question author
  1. Micro_Techie 116 Reputation points
    2021-08-09T19:54:24.94+00:00

    @Rich Matheisen :
    Thank You very much for helping me with this Code. Just to gain a better understanding, you have used try & catch block.

    1# Try will run for every identity every time & in case there is an error encountered then only catch will be executed once?
    2# Let's say if I input 100 samaccountnames & then there is either an error with 1 account (at line 50) between will the script terminate at 50 or will continue to complete the operation for the rest of the samaccountnames after 51?

    3# Also "-ErrorAction Stop" has been used twice so that in the first case if the samaccountname is inexistant then it writes the error. Second time it is used again so that incase there is an error while updating the attribute then it records that error too.

    4# Can it also catch the errors realtime instead of me defining the errors in the blocks?

    5# Where does it writes the log file output?Where can I define and how.


1 additional answer

Sort by: Most helpful
  1. Rich Matheisen 48,026 Reputation points
    2021-08-09T19:03:40.18+00:00

    Something like this:

    $List = Import-csv c:\new\input.csv
     ForEach ($User in $List) {
        Try{
            Get-ADUser -Identity $User.samaccountname -ErrorAction Stop | 
                Set-ADAccountExpiration -TimeSpan (New-TimeSpan -Days 100) -ErrorAction Stop
            # Write 'Success' to log file here
        }
        Catch{
            # Write 'Failure' to log file here
        }
    }
    

    You'll have to define what you want written to the log file, and the log file itself.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.