我可以在 powershell 脚本中写入警告而末尾不换行吗?

xdh*_*ore 3 powershell powershell-7.0

我想在 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
Run Code Online (Sandbox Code Playgroud)

这非常有效——打印黄色提示,然后读取同一行的输入——但我想知道我看到的反对使用的警告Write-Host,是否更适合找出某种打印到警告流的方法没有换行符。有没有办法做到这一点?我注意到这Write-Host似乎是一个写入信息流的包装器,但我没有看到任何方法可以在没有新行的情况下写入警告([Console]::Warning.WriteLine()例如,不存在)。

Sag*_*pre 5

你不能用 做你想做的事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使用and/or写入信息流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
Run Code Online (Sandbox Code Playgroud)

奖金

如果通过参数使用高级函数-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

Run Code Online (Sandbox Code Playgroud)

笔记

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

但是,我对此的经验有限,并且我对此主题的观察是,您最终可能必须创建异常才能遵守某些控制台环境的限制。在我看来,这有点过分了......

其他参考 About_redirects