PowerShell Get-ChildItem how to catch Exception

一世执手 提交于 2019-12-10 18:46:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!