Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Get-ChildItem how to catch Exception

Im currently programming a visual error GUI that catches any exception while processing and give's the user an "easy to understand" error message. But it seems that I can't catch any exceptions while using the Get-ChildItem cmdlet. Do I have to use a different method than try / catch?

Here's the PowerShell script:

if ($checkBox1.Checked)    {
    Try{
        Get-ChildItem -path K:\adm_spm_logdb_data\ADP\DATA |Rename-Item -newname { $($_.BaseName -split '_provide')[0] + $_.Extension };
        }catch [System.Exception]{
        $listBox1.Items.Add("An error occured while trying to process ADP-Files please check the manual!")
        }
        $listBox1.Items.Add("Please check your System files to ensure the process has finished")
    }

I tried to create an exception by using a false -path which results in a DriveNotFoundException. But it looks like I can't catch it by using try / catch.

like image 453
Tehc Avatar asked Aug 11 '16 05:08

Tehc


People also ask

How do I catch exceptions in PowerShell script?

Use the try block to define a section of a script in which you want PowerShell to monitor for errors. When an error occurs within the try block, the error is first saved to the $Error automatic variable. PowerShell then searches for a catch block to handle the error.

What does get ChildItem do in PowerShell?

Get-ChildItem displays the files and directories in the PowerShell console. By default Get-ChildItem lists the mode (Attributes), LastWriteTime, file size (Length), and the Name of the item. The letters in the Mode property can be interpreted as follows: l (link)


1 Answers

Add -ErrorAction Stop to the Get-ChildItem cmdlet:

if ($checkBox1.Checked)    {
    Try{
        Get-ChildItem -path "K:\adm_spm_logdb_data\ADP\DATA" -ErrorAction Stop |Rename-Item -newname { $($_.BaseName -split '_provide')[0] + $_.Extension };
        }catch [System.Exception]{
        $listBox1.Items.Add("An error occured while trying to process ADP-Files please check the manual!")
        }
        $listBox1.Items.Add("Please check your System files to ensure the process has finished")
    }
like image 132
Martin Brandl Avatar answered Oct 17 '22 15:10

Martin Brandl