简体   繁体   English

复制 PowerShell 的写入主机行为

[英]Replicate PowerShell's Write-Host Behavior

Something interesting I noticed about PowerShell's Write-Host behavior is that it seems to output pretty much anything as long as it's not attached to another one of it's built-in parameters.我注意到关于 PowerShell 的Write-Host行为的一些有趣的事情是,只要它没有附加到另一个内置参数,它似乎对 output 几乎没有任何影响。

For example:例如:

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)

So even though the objects to output are split by ForegroundColor it's still outputs "what what".因此,即使 output 的对象被ForegroundColor分割,它仍然输出“什么什么”。

How?如何? How can I replicate this behavior and make some sort of proxy Cmdlet to allow for this behavior?如何复制此行为并制作某种代理 Cmdlet 以允许此行为?

I have a requirement to output information to the console if some global condition is true with varying colors.如果某些全局条件在不同 colors 的情况下为真,我需要向控制台提供 output 信息。 I received this script secondhand and it was covered in我收到了这个脚本二手,它被覆盖

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

I'd like to make that a little more succinct so I wrote the following:我想让它更简洁一点,所以我写了以下内容:

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
    }
}

But calling it gives an error:但是调用它会出错:

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

what you want is the ValueFromRemainingArguments parameter attribute.您想要的是ValueFromRemainingArguments参数属性。 it stuffs all the non-bound args into the specified parameter.它将所有未绑定的参数填充到指定的参数中。 it is more-or-less the opposite of $PSBoundParameters .它或多或少与$PSBoundParameters相反。 [ grin ] [咧嘴笑]

from the MSDocs site on the subject...来自有关该主题的 MSDocs 站点...

Gets and sets a flag that specifies that the remaining command line parameters should be associated with this parameter in the form of an array.获取并设置一个标志,该标志指定剩余的命令行参数应以数组的形式与此参数相关联。 When it is not specified, false is assumed.如果未指定,则假定为 false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM