【问题标题】:Replicate PowerShell's Write-Host Behavior复制 PowerShell 的写入主机行为
【发布时间】:2019-11-02 05:01:41
【问题描述】:

我注意到关于 PowerShell 的 Write-Host 行为的有趣之处在于,只要它没有附加到另一个内置参数,它似乎就可以输出几乎任何东西。

例如:

PS> Write-Host "hello" "everyone is cool" "awesome sauce" -ForegroundColor Green "what what"
hello everyone is cool awesome sauce what what (pretend this is green)

因此,即使要输出的对象被ForegroundColor 分割,它仍然会输出“what what”。

怎么样?如何复制此行为并制作某种代理 Cmdlet 以允许此行为?

如果某些全局条件为真且颜色不同,我需要将信息输出到控制台。我收到了这个脚本,它被覆盖在

  If ($Global:SomeCondition -eq $True) {
       Write-Host "stuff" "more stuff" -ForegroundColor $VaryingColor
   }

我想让它更简洁一点,所以我写了以下内容:

Function Write-IfSomeCondition {
    Param(
        [Parameter(
            Mandatory = $True,
            ValueFromPipeline = $True)
        ][Object[]]$Object,
        [System.ConsoleColor]$ForegroundColor = (. {If ((Get-Host).UI.RawUI.ForegroundColor -ne -1) {(Get-Host).UI.RawUI.ForegroundColor} Else {[System.ConsoleColor]::White}})
    )

    If ($Condition) {
        $Object | Write-Host -ForegroundColor $ForegroundColor
    }
}

但是调用它会报错:

PS> Write-IfSomeCondition "hello" "hello" "hello" -ForegroundColor Gray
Write-IfSomeCondition : A positional parameter cannot be found that accepts argument 'hello'.

【问题讨论】:

  • 我认为你想要的与$PSBoundParamters 正好相反。查看参数的ValueFromRemainingArguments 属性。
  • @Lee_Dailey 多年的 PowerShell 并且从不知道它的存在。把它作为一个答案,我会接受它作为解决方案。太棒了!
  • 是的,例如,foreach-object 使用 ValueFromRemainingArguments 属性来处理任意数量的脚本块。 stackoverflow.com/questions/16644739/…
  • 另外注意 - 有几个 PSGallery 模块可用,它为在控制台中输出颜色添加了更多功能
  • @SomeShinyObject - 按要求发布的新答案。 [咧嘴]

标签: powershell


【解决方案1】:

您想要的是ValueFromRemainingArguments 参数属性。它将所有未绑定的参数填充到指定的参数中。它或多或少与$PSBoundParameters 相反。 [咧嘴一笑]

来自有关该主题的 MSDocs 站点...

获取并设置一个标志,该标志指定剩余的命令行参数应以数组的形式与此参数相关联。如果未指定,则假定为 false。

【讨论】:

  • 谢谢!这非常适合我正在寻找的东西
  • @SomeShinyObject - 不客气!很高兴能帮上一点忙……[grin]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-07
  • 2018-11-28
  • 2021-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多