Try Catch on Changing AD Password

Welcome Forums General PowerShell Q&A Try Catch on Changing AD Password

Viewing 2 reply threads
  • Author
    Posts
    • #207396
      Participant
      Topics: 66
      Replies: 71
      Points: 510
      Rank: Major Contributor

      I have been banging my head on this one and I just do not see my error.

      Essentially, I created a CMDLET that is part of a CMDLET module which will allow our technicians to quickly change a users password without having to go into AD.

      I want to Catch the error from an invoke-command statement to show what the user did wrong…for instance, if the password does not adhere to the DC’s password complexity policy.

      I shaved the cmdlet to show the problem. Here is the cmdlet that is part of a bigger CMDLet Module.

      Get-TPAdminLogin is a cmdlet that grabs a domain admin account which then requires authentication and then assigns credentials to the $TPCred variable used in the Invoke-Command statement.

       

      Function Set-TPADpassword
      {
      try
      {
      Get-TPAdminLogin
      $Login = 'tptest3'
      $pwd1 = Read-Host -Prompt "Provide New Password" -AsSecureString
      
      Invoke-Command -ComputerName 10.221.21.3 -ScriptBlock { Set-ADAccountPassword -Identity $Using:Login -Reset -NewPassword $Using:pwd1 } -Credential $TPCred -ErrorAction Stop
      Write-host "Invoke-command completed"
      }
      catch
      {
      Write-output "Some Shit happened"
      Write-Output $error[0].Exception
      }
      }

      The problem is that Write-Output $error[0].Exception never writes to the Output stream.   It is in fact there as illustrated below.  I put a password that was too short but I only see ‘Some Shit happened”.  If I manually enter in $error[0].Exception, I see the error it generated.

      PS H:\> Set-TPADpassword
      Provide New Password: ****
      Some Shit happened
      PS H:\> $error[0].exception
      The password does not meet the length, complexity, or history requirement of the domain.
      PS H:\>
    • #207441
      Participant
      Topics: 0
      Replies: 3
      Points: 40
      Rank: Member

      Hi,

      Unable to replicate your issue, however, have you tried:

      Write-Output $_.Exception

      Rather than referencing element zero of the $error variable in your catch block?

      • This reply was modified 2 months, 3 weeks ago by moezus08.
    • #207516
      Participant
      Topics: 66
      Replies: 71
      Points: 510
      Rank: Major Contributor

      Yes, that seemed to work.  Wish I knew the ‘why’ of it.

      S H:\> Set-TPADpassword tptest3
      Provide New Password: ****
      Confirm Password: ****
      Some Shit happened with the password.
      The password does not meet the length, complexity, or history requirement of the domain.
      PS H:\>
Viewing 2 reply threads
  • You must be logged in to reply to this topic.