Write-Error在类方法中使用时不会产生有用的信息| Powershell

问题描述 投票:1回答:1

我使用了带有和不带有类的方法,并且Write-Error似乎产生不同的输出。如果是类,则不指定函数,行号始终为1,1

function oper1() {
    Try {
        [string] $cmd = ".\some_exe_which_does_not_exist.exe"
        iex $cmd 
    }
    Catch {
        Write-Error $_.Exception.Message
    }
}

oper1

以上输出:

oper1:术语'。\ some_exe_which_does_not_exist.exe'不是识别为cmdlet,函数,脚本文件或可操作文件的名称程序。检查名称的拼写,或者是否包含路径,验证路径正确,然后重试。在F:\ debug \ encryption_concat_tests \ Untitled1.ps1:11个字符:1+ oper1+ ~~~~~+ CategoryInfo:未指定:(:) [Write-Error],WriteErrorException+ FullyQualifiedErrorId:Microsoft.PowerShell.Commands.WriteErrorException,oper1

当我在一个类中包含相同的函数时,我得到了:

class Operator {
    [void] oper1() {
        Try {
            [string] $cmd = ".\some_exe_which_does_not_exist.exe"
            iex $cmd 
        }
        Catch {
            Write-Error $_.Exception.Message
        }
    }
}

[Operator] $operator = New-Object Operator
$operator.oper1()

术语'。\ some_exe_which_does_not_exist.exe'不被识别为cmdlet,函数,脚本文件或可运行程序的名称。检查名称的拼写,或者是否包含路径,请验证路径正确,然后重试。 在第1行:1个字符:1+ F:\ debug \ encryption_concat_tests \ Untitled1.ps1+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo:未指定:(:) [Write-Error],WriteErrorException+ FullyQualifiedErrorId:Microsoft.PowerShell.Commands.WriteErrorException

类内部方法的这种行为可能是什么原因?

powershell write-error
1个回答
0
投票

顺便说一句:Invoke-Expression (iex) should generally be avoided;绝对Invoke-Expression-只需直接调用它,如下所示。


在PowerShell类方法中:

  • 请勿使用iex,因为类的设计目的不是发出non-termination错误。

  • 相反,仅通过与[void]语句进行throwing传递错误,或通过not捕获termination错误(包括.NET方法的异常和使用[C0 ])。

这是您的代码的正确版本。

this GitHub issue
© www.soinside.com 2019 - 2024. All rights reserved.