PowerShell Get-ChildItem如何捕获异常

Bya*_*aku 3 powershell exception try-catch

我目前正在编写一个可视错误GUI,在处理过程中捕获任何异常,并为用户提供"易于理解"的错误消息.但似乎在使用Get-ChildItemcmdlet 时我无法捕获任何异常.我是否必须使用与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")
    }
Run Code Online (Sandbox Code Playgroud)

我试图通过使用虚假创建例外-path,其导致DriveNotFoundException.但看起来我无法通过使用try/catch来捕获它.

Mar*_*ndl 6

添加-ErrorAction StopGet-ChildItemcmdlet:

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")
    }
Run Code Online (Sandbox Code Playgroud)