你不能做你想做的事Write-Warning
。
因此,我将回答您的其他问题。
Write-Host
非常适合在 PowerShell 5+ 脚本中使用。
如果您查看建议不要使用它的文章,您会注意到绝大多数(如果不是全部)是在 PowerShell 5 引入之前编写的。
如今,Write-Host
是一个包装器Write-Information
。
官方文档证实了这一点:
从 Windows PowerShell 5.0 开始,Write-Host
它是一个包装器,
Write-Information
允许您使用Write-Host
它来向信息流发出输出。这可以捕获或抑制使用写入的数据,Write-Host
同时保持向后兼容性。
首$InformationPreference
选项变量和-InformationAction
公共参数不影响Write-Host
消息。此规则的例外是
-InformationAction Ignore
,它有效地抑制了
Write-Host
输出。
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