0

I have this test script to change the Administrator password on a list of servers. I have set the script to log errors if the server can't be ping'd or account can't be found etc. However in addtion to this i'd like to capture any other errors that take place and also add those to the log file. I know you can use the "Try and Catch" for error handling but havn't had any luck so far.

Would someone be kind enough to show how to do it?

Here is the script

    $date = Get-Date
$user = "Administrator"
$newpwd = "MyPassword"

     $servers = gc C:\servers.txt

foreach ($server in $servers) 
{ 


  $ping = new-object System.Net.NetworkInformation.Ping

  $Reply = $null 
  $Reply = $ping.send($server)


  if($Reply.status -like 'Success')
    {

    $Admin=[adsi]("WinNT://" + $server + "/$user, user")

    if($?) 
      {
       $Admin.SetPassword($newpwd)

     if($?)

      {Add-Content -path C:\Audit\logs\servers-reset.csv -Value "$server,  Succsess the $user password was changed. , $date"}

      else
        {Add-Content -path C:\Audit\logs\servers-reset.csv -Value "$server, Error: FAILED to change the password. , $date"}
      }  
      else
      {
      Add-Content -path C:\Audit\logs\servers-reset.csv -Value "$server, Error: The $user user account was not found on the server. , $date"}
      }    
      else
      {
      Add-Content -path C:\Audit\logs\servers-reset.csv -Value "$server, Error: Ping FAILED could not connect. , $date"
      }

1 Answer 1

2

If you want to write exceptions to the log right after they were thrown, you could use a trap. Add something like this to you script:

trap [Exception] {

    #Add message to log
    Add-Content -Path test.csv -Value "$server, $($_.Exception.Message), $(Get-Date)"

    #Continue script
    continue; 
}

That will log all exceptions (not all errors).

If you want all errors, you can access them using $Error. It's an arraylist containing every error during your sessions(script). The first item $Error[0] is the latest error. This however, is not something that fits directly into an csv file without formatting it.

Sign up to request clarification or add additional context in comments.

5 Comments

Thankyou could you show me where to place this within the script?
I'd like to capture the exceptions errors if the other errors arn't true and include those in the log so i know what went wrong.
I didn't understand the last one there. To use the trap, place the code in your script, I'd prefer to put it on the start, right after param() if you have that. Before you start using cmdlets like Get-Date, Get-Content
ok thanks i'll have a a try....don't have param() set, the script is just as posted.
Ok i manged to get it sorted for my needs. Thanks again Graimer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.