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.
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.
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)
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With