try..catch不工作?

时间:2016-03-18 16:45:10

标签: powershell

我有一个try..catch声明,而且它没有捕获,PS v4。

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

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

Get-Content : Cannot find path 'C:\test.xml' because it does not exist.
At C:\test.ps1:3 char:29
+     [xml]$script:fileInfo = Get-Content $configFile
     + CategoryInfo          : ObjectNotFound: (C:\test.xml:String) [Get-Content], ItemNotFoundException
     + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand

1 个答案:

答案 0 :(得分:4)

您需要更改对Get-Content的调用以使其停止执行,从而可以捕获错误,添加 -ErrorAction stop

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