PowerShell Get-ChildItem如何捕获异常

时间:2016-08-11 05:47:44

标签: powershell exception try-catch

我目前正在编写一个可视错误GUI,可以在处理时捕获任何异常,并为用户提供“易于理解”的错误消息。但似乎在使用Get-ChildItem cmdlet时我无法捕获任何异常。我是否必须使用与try / catch不同的方法?

这是PowerShell脚本:

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")
    }

我尝试使用假-path创建一个异常,从而产生DriveNotFoundException。但看起来我无法通过使用try / catch来捕获它。

1 个答案:

答案 0 :(得分:6)

-ErrorAction Stop添加到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")
    }