使用Write-Error写入Powershell中的错误流

M. *_*ley 13 powershell write-error

为什么Powershell的Write-Errorcmdlet 不能为我工作?我的输出看起来不像文档中的示例:

PS C:\> Write-Error "This is an error"
Write-Error "This is an error" : This is an error
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException
Run Code Online (Sandbox Code Playgroud)

我一直期待输出类似于Write-Warning:

PS H:\> Write-Warning "This is a warning"
WARNING: This is a warning
Run Code Online (Sandbox Code Playgroud)

Write-Errorabout_preference_variables文档我认为我不应该看到任何例外?

PS H:\> Get-Help About_Preference_Variables

$ErrorActionPreference
----------------------

...

        PS> $erroractionpreference                      
        Continue        # Display the value of the preference.                

        PS> write-error "Hello, World"                  
                                # Generate a non-terminating error.

        write-error "Hello, World" : Hello, World       
                                # The error message is displayed and
                                  execution continues.

        PS> write-error "Hello, World" -ErrorAction:SilentlyContinue
                                # Use the ErrorAction parameter with a 
                                  value of "SilentlyContinue".
        PS>                                             
                                # The error message is not displayed and
                                  execution continues.
Run Code Online (Sandbox Code Playgroud)

Nei*_*eil 16

要获得类似于写警告的输出,您可以这样做:

$Host.UI.WriteErrorLine("This is an error")
Run Code Online (Sandbox Code Playgroud)

(克里斯西尔斯为这个答案道具)

  • 不要这样做.`WriteErrorLine`是一种UI方法,这就是为什么Zenexer说什么都没有被重定向到stderr.请参阅Keith Hill的回答和http://stackoverflow.com/questions/4998173/how-do-i-write-to-standard-error-in-powershell. (3认同)
  • 有趣的是,这写入stdout,而不是stderr.PowerShell ISE似乎不是echo stderr,虽然正常的PowerShell提示符(没有应用特殊格式).尝试在每个中运行`[System.Console] :: Error.WriteLine('test')`,看看会发生什么. (2认同)

Kei*_*ill 6

为什么你认为它不起作用?请记住,PowerShell可以区分上述非终止错误和终止执行时出现的错误throw 'Access denied.'.非终止错误被写入stderr并记录在$ error集合中,但它们不会停止处理脚本.当您处理(例如删除或复制)一堆文件时,此功能非常方便.您想知道哪些文件无法处理,但您不希望整个操作在第一个出错的文件上停止.

PowerShell还为您提供了"转换"非终止错误以终止错误的选项,例如

Remove-Item c:\file-doesnt-exist -ErrorAction Stop; "Did I get here"
Run Code Online (Sandbox Code Playgroud)

请注意,在这种情况下,执行会停止,并且不会在结尾处打印出字符串.尝试没有-ErrorAction Stop,你会看到错误,但你也会看到字符串"我有没有到达这里".

如果要控制Catogory信息,可以使用-Category参数,如下所示:

PS> write-error "foo" -Category 'InvalidResult'
write-error "foo" -Category 'InvalidResult' : foo
    + CategoryInfo          : InvalidResult: (:) [Write-Error], WriteErrorExce..
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException
Run Code Online (Sandbox Code Playgroud)

但WriteErrorException是这个cmdlet引发错误的机制(我认为).有一个Exception参数,但我没有运气使用它.