代码之家  ›  专栏  ›  技术社区  ›  Emil

使用脚本中的参数执行PowerShell命令

  •  1
  • Emil  · 技术社区  · 6 年前

    这是我的PowerShell脚本中的哈希表(使用 获取psreadlineoption ):

    $theme = @{}
    $theme["CommentForegroundColor"] = "DarkGreen"
    $theme["CommentBackgroundColor"] = "Black"
    $theme["KeywordForegroundColor"] = "Green"
    $theme["KeywordBackgroundColor"] = "Black"
    

    我正在尝试使用设置PowerShell主题颜色 设置psreadlineoption 命令:

    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 will be set to White
    -TokenKind Command -BackgroundColor White
    Set-PSReadlineOption : Cannot bind parameter 'TokenKind'. Cannot convert value "-Tok
    enKind Command -BackgroundColor White" to type "Microsoft.PowerShell.TokenClassifica
    tion". Error: "Unable to match the identifier name -TokenKind Command -BackgroundCol
    or White to a valid enumerator name. Specify one of the following enumerator names a
    nd try again:
    None, Comment, Keyword, String, Operator, Variable, Command, Parameter, Type, Number
    , Member"
    At C:\Users\...\PowerShellColors.ps1:88 char:28
    +     & Set-PSReadlineOption $params
    

    我做错了什么?

    1 回复  |  直到 6 年前
        1
  •  3
  •   marsze    6 年前

    你把你所有的论点都当作 单一的 字符串,这不是您想要的。

    你想做的就是 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"