【问题标题】:try..catch not working? [duplicate]尝试..catch 不起作用? [复制]
【发布时间】:2016-03-18 16:45:10
【问题描述】:

我有一个try..catch 声明,但它没有引起注意,PS v4。

Function ReadFile ([string] $configfile) {
    try {
        [xml]$script:fileInfo = Get-Content $configFile
    } catch {
        Write-Host $_.Exception.Message
    }
}

它永远不会捕获,但它在控制台中出错?以下是控制台错误:

获取内容:找不到路径“C:\test.xml”,因为它不存在。
在 C:\test.ps1:3 char:29
+ [xml]$script:fileInfo = 获取内容 $configFile
     + CategoryInfo : ObjectNotFound: (C:\test.xml:String) [Get-Content], ItemNotFoundException
     + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand

【问题讨论】:

    标签: powershell


    【解决方案1】:

    您需要更改对 Get-Content 的调用,使其停止执行,这样才能捕获错误,添加 -ErrorAction stop

    Function ReadFile ([string] $configfile)
    {
        Try {
                [xml]$script:fileInfo = Get-Content $configFile -ErrorAction stop
        }
        Catch {
                Write-Host $_.Exception.Message
        }
    }
    

    【讨论】:

    • 重新表述:Try-Catch 仅适用于终止异常。
    • 成功了!有没有办法在全局级别为特定脚本设置它?还是每次调用 PS 命令时都需要指定这个?谢谢!
    • 有几篇关于这个主题的脚本专家文章,例如this one
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 2021-08-04
    相关资源
    最近更新 更多