Error handling

This topic contains 4 replies, has 3 voices, and was last updated by  Don Jones 2 years, 2 months ago.

  • Author
    Posts
  • #27553

    Ian Fermer
    Participant

    Hi,

    I'm trying to handle errors in my powershell script, read up a lot about this but as my script contains exceptions from and cmd being run, not sure how I can get the silentlycontinue and stop complaining done 🙂

    If($Result)
    {
    $Result
    foreach($Folder in $Result)

    {
    #Remove user folder
    $path = $Folder.FileName
    cmd.exe /c "RD /S /Q `"$path`""
    }

    }

  • #27554

    Ian Fermer
    Participant

    On this

    I have used the try and catch statements to output to a log file but no luck on this.

    Error comes out as


    cmd.exe : The directory name is invalid.
    At line:55 char:5
    + cmd.exe /c "RD /S /Q `"$path`""
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (The directory name is invalid.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

    cmd.exe : The directory name is invalid.
    At line:55 char:5
    + cmd.exe /c "RD /S /Q `"$path`""
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (The directory name is invalid.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

    cmd.exe : The directory name is invalid.
    At line:55 char:5
    + cmd.exe /c "RD /S /Q `"$path`""
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (The directory name is invalid.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

  • #27555

    Ian Fermer
    Participant

    ...and solved, used $erroractionpreference = "silentlycontinue"

    If anyone is interested 🙂

  • #27558

    Rob Simmers
    Participant

    The default of Powershell should already be set to continue, you can check it by simply doing this:

    PS C:\Windows\System32\WindowsPowerShell\v1.0> $ErrorActionPreference
    Continue
    

    Also, RD (Remove Directory) is available in native Powershell as Remove-Item which has an alias of none other than RD, so there is no need to call an external executable.:

    PS C:\Windows\System32\WindowsPowerShell\v1.0> rd
    cmdlet Remove-Item at command pipeline position 1
    Supply values for the following parameters:
    Path[0]: 
    

    the command would be something like this...

    Remove-Item -Path $path -Force -ErrorAction SilentlyContinue
    
  • #27564

    Don Jones
    Keymaster

    Consider reading through "The Big Book of PowerShell Error Handling," under eBooks in our Resources menu here.

    However, you can't use Try/Catch with external executables. That only works "inside" PowerShell. Externals don't throw errors into the error pipeline, they just print error messages as text, which PowerShell dutifully passes along.

You must be logged in to reply to this topic.