【问题标题】:PowerShell Get-ChildItem how to catch ExceptionPowerShell Get-ChildItem 如何捕获异常
【发布时间】:2016-12-17 16:59:28
【问题描述】:

我目前正在编写一个可视化错误 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 来捕捉它。

【问题讨论】:

    标签: powershell exception try-catch


    【解决方案1】:

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

    【讨论】:

    • 谢谢你成功了!我会尽快接受这个答案。
    猜你喜欢
    • 1970-01-01
    • 2011-02-22
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多