【发布时间】: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