我可以在末尾没有换行符的情况下在 powershell 脚本中编写警告吗?

Can I Write-Warning in a powershell script without a newline at the end?

我想在 PowerShell 中打印警告作为提示,然后在同一行阅读答案。问题是 Write-Warning 在消息末尾打印换行符,而另一种选择 Read-Host -Prompt 不会将提示打印到警告流(或以黄色打印)。我看过 Write-Warning -WarningAction Inquire,但我认为这有点冗长并且提供了我不想要的选项。

我做过的最好的是:

  $warningMsg= "Something is wrong. Do you want to continue anyway Y/N? [Y]:"
  Write-Host -ForegroundColor yellow -NoNewline $warningMsg
  $cont = Read-Host

这很好——打印黄色提示,然后读取同一行的输入——但我想知道我看到的反对使用 Write-Host 的警告,如果它更适合想出一些方法来打印到没有换行符的警告流。有没有办法做到这一点?我注意到 Write-Host 似乎是写入信息流的包装器,但我没有看到任何没有换行的方法来写入警告(例如 [Console]::Warning.WriteLine() 不存在).

你不能用 Write-Warning 做你想做的事。

因此,我会回答您的其他问题。 Write-Host 非常适合在 PowerShell 5+ 脚本中使用。

如果您查看反对使用它的文章,您会发现绝大多数(如果不是全部)都是在引入 PowerShell 5 之前写的。

现在,Write-HostWrite-Information 的包装。

official documentation 证实了这一点:

Starting in Windows PowerShell 5.0, Write-Host is a wrapper for Write-Information This allows you to use Write-Host to emit output to the information stream. This enables the capture or suppression of data written using Write-Host while preserving backwards compatibility.

The $InformationPreference preference variable and -InformationAction common parameter do not affect Write-Host messages. The exception to this rule is
-InformationAction Ignore, which effectively suppresses Write-Host output.

使用 Write-Host 和/或 Write-information 写入信息流不会对您的输出字符串造成问题。

Stream #    Description          Introduced in
1           Success Stream       PowerShell 2.0
2           Error Stream         PowerShell 2.0
3           Warning Stream       PowerShell 3.0
4           Verbose Stream       PowerShell 3.0
5           Debug Stream         PowerShell 3.0
6           Information Stream   PowerShell 5.0
*           All Streams          PowerShell 3.0

奖金

如果您通过 -InformationAction 参数使用高级函数,您还可以控制信息流的可见性,前提是您还将给定的参数值绑定到函数中的 Write-Host 语句。

例如,如果您希望默认禁用信息流,除非另有要求:

function Get-Stuff {
     [CmdletBinding()]
     param ()

     if (!$PSBoundParameters.ContainsKey('InformationAction')) {
        $InformationPreference = 'Ignore'
     }
     Write-Host 'This is the stuff'  -InformationAction $InformationPreference -ForegroundColor Green
}

# Hidden by default
Get-Stuff
# Force it to show
Get-Stuff -InformationAction Continue

备注

虽然从技术上讲无法使用 Write-Warning -NoNewLine,但您可以考虑操纵光标位置并将其重置到上一行的末尾,因此执行相同的操作。

但是,我对此经验有限,我对这个主题的观察是您可能最终不得不创建例外以符合某些控制台环境的限制。在我看来,这有点过分了...

其他参考资料 About_redirections