首页 > 解决方案 > 使用脚本中的参数执行 powershell 命令

问题描述

这是我的 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:无法绑定参数“TokenKind”。无法转换价值“-Tok
enKind Command -BackgroundColor White" 输入 "Microsoft.PowerShell.TokenClassifica
化”。错误:“无法匹配标识符名称 -TokenKind 命令 -BackgroundCol
或 White 为有效的枚举数名称。指定以下枚举器名称之一
再试一次:
无、注释、关键字、字符串、运算符、变量、命令、参数、类型、数字
, 成员”
在 C:\Users\...\PowerShellColors.ps1:88 char:28
+ & 设置-PSReadlineOption $params

我做错了什么?

标签: powershellarguments

解决方案


您将所有参数作为单个字符串传递,这不是您想要的。

你想做的事情叫做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"

推荐阅读