PowerShell Get-ChildItem how to catch Exception

12,611

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")
    }
Share:
12,611
Tehc
Author by

Tehc

Updated on June 14, 2022

Comments

  • Tehc
    Tehc almost 2 years

    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.