1

Write-Error 的输出在具有返回值的方法中被省略(即不是 void):

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 方法也会忽略输出,就好像调用堆栈以某种方式“中毒”了一样。是的(虽然在这个例子中没有显示)调用 void 方法的 void 方法有效。

有人可以解释一下这种行为还是我只是发现了一个错误?

4

1 回答 1

2

目前有一个错误开放。问题实际上是Write-Error在 void 方法中工作。

按照设计,目的是您应该使用Throw在类中产生错误。

这是您的脚本的修改版本

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 无法在返回非空值的类方法中工作

于 2020-01-22T22:48:33.160 回答