Write-Error (PowerShell) 的奇怪行为:具有 return 值的方法内部没有输出

Strange behaviour of Write-Error (PowerShell): no output from within methods with a return value

Write-Error 的输出在具有 return 值(即不为空)的方法中被忽略:

Class MyClass {
    [void]MethodWithoutReturnValue([string]$Msg) {
        Write-Error "MyClass.MethodWithoutReturnValue(): $Msg"
    }

    [bool]MethodWithReturnValue([string]$Msg) {
        Write-Error "MyClass.MethodWithReturnValue(): $Msg"
        $this.MethodWithoutReturnValue("this won't work either")
        return $true
    }
}

[MyClass]$obj = [MyClass]::new()
$obj.MethodWithoutReturnValue('this error will show up')
[bool]$Result = $obj.MethodWithReturnValue('this error will NOT show up')

我期待三条错误消息,但只收到一条。请注意,从 bool 方法调用 void 方法也会省略输出,就好像调用堆栈是 "poisoned" 一样。是的(虽然未在此示例中显示)调用 void 方法的 void 方法有效。

谁能解释一下这种行为,还是我只是发现了一个错误?

目前有一个 bug 未解决。 问题实际上是 Write-Error 在 void 方法中工作。

根据设计,您应该使用 Throw 从 class.

中产生错误

这是您的脚本的修改版本

Class MyClass {
    [void]MethodWithoutReturnValue([string]$Msg) {
       Throw "MyClass.MethodWithoutReturnValue(): $Msg"
    }

    [bool]MethodWithReturnValue([string]$Msg) {
       Throw "MyClass.MethodWithReturnValue(): $Msg"
        $this.MethodWithoutReturnValue("this won't work either")
        return $true
    }
}

[MyClass]$obj = [MyClass]::new()
$obj.MethodWithoutReturnValue('this error will show up')
[bool]$Result = $obj.MethodWithReturnValue('this error will NOT show up')

补充说明

使用 Throw 将停止您的脚本,这样脚本就不会继续执行。 为防止这种情况,请使用 Try{}Catch{} 语句。

[MyClass]$obj = [MyClass]::new()
Try {
    $obj.MethodWithoutReturnValue('this error will show up')
    }
Catch {
    Write-Error $_
}
[bool]$Result = $obj.MethodWithReturnValue('this error will NOT show up')

# I love Cyan
Write-Host 'Second error not being in a try catch mean this will not get printed' -ForegroundColor Cyan

参考

Github -Write-Error fails to work in class methods that return a non-void value