PowerShell Get-ChildItem如何捕获异常 [英] PowerShell Get-ChildItem how to catch Exception

查看:196
本文介绍了PowerShell Get-ChildItem如何捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在编程一个可视化错误GUI,该GUI在处理过程中会捕获任何异常,并向用户提供易于理解的错误消息。但是,在使用 Get-ChildItem cmdlet时,似乎看不到任何异常。我是否必须使用不同于try / catch的方法?

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?

以下是PowerShell脚本:

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

我试图通过使用错误的-路径创建一个异常,结果导致 DriveNotFoundException

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.

推荐答案

添加 -ErrorAction停止 Get-ChildItem cmdlet:

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

这篇关于PowerShell Get-ChildItem如何捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆