Error handling

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 :slight_smile:

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

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

}

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

…and solved, used $erroractionpreference = “silentlycontinue”

If anyone is interested :slight_smile:

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

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.