这是我的Powershell脚本中的哈希表(使用Get-PSReadlineOption提取的数据):
$theme = @{}
$theme["CommentForegroundColor"] = "DarkGreen"
$theme["CommentBackgroundColor"] = "Black"
$theme["KeywordForegroundColor"] = "Green"
$theme["KeywordBackgroundColor"] = "Black"
我正在尝试使用Set-PSReadlineOption命令设置Powershell主题颜色:
foreach ($colorTokenKey in $theme.keys) {
$c=$theme[$colorTokenKey]
echo "$colorTokenKey will be set to $c"
$colorTokenArgs = $colorTokenKey.Replace("ForegroundColor"," -ForegroundColor")
$colorTokenArgs = $colorTokenArgs.Replace("BackgroundColor"," -BackgroundColor")
$colorTokenArgs = $colorTokenArgs.Split(" ")
$tokenKind = $colorTokenArgs[0]
$tokenForegroundOrBackground = $colorTokenArgs[1]
$params = "-TokenKind $tokenKind $tokenForegroundOrBackground $c"
echo $params
& Set-PSReadlineOption $params
}
但是当我运行它时,我得到
CommandBackgroundColor将设置为白色
-TokenKind命令-BackgroundColor白色
Set-PSReadlineOption:无法绑定(bind)参数“TokenKind”。无法转换值“-Tok
enKind Command -BackgroundColor White”以键入“Microsoft.PowerShell.TokenClassifica
tion“。错误:”无法匹配标识符名称-TokenKind命令-BackgroundCol
或白色为有效的枚举器名称。指定以下枚举器名称之一
nd再试一次:
无,注释,关键字,字符串,运算符,变量,命令,参数,类型,数字
,成员”
在C:\ Users \ ... \ PowerShellColors.ps1:88 char:28
+&Set-PSReadlineOption $ params
我做错了什么?
最佳答案
您将所有参数作为单个字符串传递,这不是您想要的。
您想要做的就是splatting。
将您的最后几行更改为此:
$params = @{
"TokenKind" = $tokenKind
$tokenForegroundOrBackground = $c
}
Set-PSReadlineOption @params
另外,请注意,您必须传递参数而不将传递给前导
-
!因此,您也必须更改此设置:$colorTokenArgs = $colorTokenKey.Replace("ForegroundColor"," ForegroundColor")
$colorTokenArgs = $colorTokenArgs.Replace("BackgroundColor"," BackgroundColor")
(或者也许首先要对它进行不同的定义。)
稍微有点怪异的替代方法是使用Invoke-Expression,该命令将字符串作为命令执行:
Invoke-Expression "Set-PSReadlineOption $params"
关于powershell - 使用脚本中的参数执行powershell命令,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54303702/