问题
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.
回答1:
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")
}
来源:https://stackoverflow.com/questions/38888149/powershell-get-childitem-how-to-catch-exception