【发布时间】:2021-02-17 05:22:09
【问题描述】:
在 Powershell 中,如果你写输出一些行然后抛出一个错误,你会期望得到发生在错误之前的输出。所以如果你执行这个:
Write-Output ("test output 1")
Write-Output ("test output 2")
Write-Output ("test output 3")
Write-Output ("test output 4")
Write-Output ("test output 5")
throw "pretend error"
您将按预期得到:
test output 1
test output 2
test output 3
test output 4
test output 5
pretend error
At C:\Powershell\Test.ps1:7 char:1
+ throw "pretend error"
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (pretend error:String) [], RuntimeException
+ FullyQualifiedErrorId : pretend error
但是,如果您在数组中写入输出一堆对象,然后抛出错误,则数组的写入输出(以及之后的任何内容)永远不会出现。所以如果你运行这个:
Write-Output ("test output 1")
Write-Output ("test output 2")
Write-Output ("test output 3")
Write-Output ("test output 4")
Write-Output ("test output 5")
$testlist = @()
$count = 1
While($count -lt 6)
{
$testobj = new-object psobject -prop @{Name="array object $count"}
$testlist += $testobj
$count +=1
}
Write-Output $testlist
Write-Output ("test output 6")
Write-Output ("test output 7")
throw "pretend error"
...在“测试输出 5”之后,您没有得到任何输出。好像输出数组会使所有内容都被缓冲,然后错误会丢失缓冲区。与 Powershell 使用带有数组的管道的方式有关吗?
所以我的问题是:我需要做些什么来确保写入输出不会由于后续错误而丢失。这使得日志记录非常困难。
这是在 Powershell 5.1 中
【问题讨论】:
标签: powershell