Handling errors

Welcome Forums General PowerShell Q&A Handling errors

This topic contains 5 replies, has 2 voices, and was last updated by

 
Participant
4 years, 3 months ago.

  • Author
    Posts
  • #17341

    Participant
    Points: 39
    Rank: Member

    Hi,

    I'm trying to learn how to handle errors on PowerShell.

    I've tried to use the text inside the $error[0] variable to know what kind of error the command got.
    Something like this:

    PS C:\> Get-ADUser vtulio
    Get-ADUser : Não é possível localizar um objeto com identidade: 'vtulio' em:
    'DC=axxiom1,DC=local'.
    No linha:1 caractere:1
    + Get-ADUser vtulio
    + ~~~~~~~~~~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (vtulio:ADUser) [Get-ADUser], AD
       IdentityNotFoundException
        + FullyQualifiedErrorId : Não é possível localizar um objeto com identidad
       e: 'vtulio' em: 'DC=axxiom1,DC=local'.,Microsoft.ActiveDirectory.Managemen
      t.Commands.GetADUser

    So I've tried to use the "ObjectNotFound" like this:

    if ($error[0] -like "*ObjectNotFound*"){Write-Host "Object not found"}

    And it returned me nothing...

    Now I'm using something like that:

    $ErrorActionPreference = "SilentlyContinue"
    
    Write-Host "The folders below doesn't have any user associated:"
    $Names = Get-ChildItem \\server\users$ | select -Expand Name
    Write-Host
    foreach ($Name in $Names) {Get-ADUser $Name | Out-Null;if ($?){}else{Write-Host "$Name"}}
    Write-Host
    Write-Host
    $ErrorActionPreference = "Continue"

    Using the "$?" is the better way?
    This is something that I want and I really don't understand on PowerShell.
    How to handle different errors? Even when the command is not found...

  • #17342

    Keymaster
    Points: 1,639
    Helping HandTeam Member
    Rank: Community Hero

    Have you read "The Big Book of PowerShell Error Handling," on the Ebooks page under the Resources menu?

    $? is not a good approach.

  • #17343

    Participant
    Points: 39
    Rank: Member

    Don Jones,

    I will now =]
    Thanks!

  • #17456

    Participant
    Points: 39
    Rank: Member

    Hi, I'm reading the material you indicated to me =]

    [EDITED]
    oh..... just forget about it... "immediately" means right before the cmdlet you want to check... it's not about time =/
    sorry... lost me in translation...

    [OLD TEXT]
    On this part I felt lost:

    "Just be aware that the value of this variable is reset after every statement. You must check its value immediately after the command you're interested in, or it will be overwritten (probably to True). Figure 2.8 demonstrates this behavior. The first time $? is checked, it is set to False, because the Get-Item encountered an error. The second time $? was checked, it was set to True, because the previous command was successful; in this case, the previous command was “$?” from the first time the variable's value was displayed."

    How can I see if the value has been restarted?

    Tried this:

    PS C:\> get-something
    get-something : O termo 'get-something' não é reconhecido como nome de cmdlet,
    função, arquivo de script ou programa operável. Verifique a grafia do nome ou,
    se um caminho tiver sido incluído, veja se o caminho está correto e tente
    novamente.
    No linha:1 caractere:1
    + get-something
    + ~~~~~~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (get-something:String) [], Comma
       ndNotFoundException
        + FullyQualifiedErrorId : CommandNotFoundException
    
    PS C:\> $?
    False
    

    Then I've tried to do the same but waiting more than half an hour to do the "$?" check... And it returned "False" again. It wasn't supposed to be "true" if it's reseted?

    Just trying to understand...

  • #17458

    Keymaster
    Points: 1,639
    Helping HandTeam Member
    Rank: Community Hero

    $? is *really* a poor way to do error handling. You should instead use -ErrorAction and a Try/Catch block. Within the Catch block, you can check $_ or $error[0] to see the error that happened.

  • #17473

    Participant
    Points: 39
    Rank: Member

    Don Jones,

    Now that I'm reading the book I've noticed that...
    Great material that you guys are offering us.

    Thanks one more time for helping who is starting on PowerShell =]

The topic ‘Handling errors’ is closed to new replies.