Error message in log

This topic contains 5 replies, has 2 voices, and was last updated by Profile photo of Curtis Smith Curtis Smith 8 months ago.

  • Author
    Posts
  • #54564
    Profile photo of Wei-Yen Tan
    Wei-Yen Tan
    Participant

    Hi,

    I am trying to append the error produced by the erroneous directory path. I am wondering why it is not adding into the error log?

    $tested = 'c:\testswtgreg', 'c:\sadfdsafsafsagsa'
    try {
        Get-ChildItem $tested | foreach-object { Remove-item $_ -Recurse -Force -ErrorVariable myerr -ErrorAction Stop }
    } catch {
        
        $myerr | Out-File c:\temp\error.txt -Append
    }
    
  • #54566
    Profile photo of Wei-Yen Tan
    Wei-Yen Tan
    Participant

    i know why,

    Ihad trhe error variable stop at the wrong place.

    The catch in that block is actually referencing Get-ChildItem $tested

    so it really should be Get-ChildItem $tested -ErrorAction Stop -ErrorVariable myerr

  • #54567
    Profile photo of Curtis Smith
    Curtis Smith
    Participant

    Hi Wei,
    You only have the -ErrorAction Stop on the Remove-item, but the script is actually erring on Get-ChiltItem, not Remove-item.

    Add -ErrorAction Stop to your Get-ChildItem.

    Also, you don't have to specify the ErrorVariable, you can use $_ to get the current error.

    $tested = 'c:\testswtgreg', 'c:\sadfdsafsafsagsa'
    try {
        Get-ChildItem $tested -ErrorAction Stop | foreach-object { Remove-item $_ -Recurse -Force -ErrorAction Stop }
    } catch {
        $_.CategoryInfo.Activity
        $_.Exception.Message
    }
  • #54568
    Profile photo of Curtis Smith
    Curtis Smith
    Participant

    Hey Wei,
    Good job debugging it while I was replying. 🙂

  • #54569
    Profile photo of Wei-Yen Tan
    Wei-Yen Tan
    Participant

    Thanks for the last bit. Thats exactly what i need. Because I need to append detailed information to the log.

    I am presuming then in this line:

    Remove-item $_ -Recurse -Force -ErrorAction Stop

    I can create its own block and add the details in that one too?

    Thanks for this. What I have been trying to work on for a while can finally be finished.

  • #54572
    Profile photo of Curtis Smith
    Curtis Smith
    Participant

    That is correct if either one of those those a terminating error, which is what will happen with -ErrorAction Stop, then they get sent to the catch block which will work with the current error whether it was on Get-ChildItem or Remove-Item.

You must be logged in to reply to this topic.