【问题标题】:Execute powershell command with arguments from script使用脚本中的参数执行 powershell 命令
【发布时间】:2019-01-22 08:04:07
【问题描述】:

这是我的 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

我做错了什么?

【问题讨论】:

    标签: powershell arguments


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!我会在很长一段时间内跌跌撞撞地陷入“飞溅”(如果完全跌倒的话)......
    • @Emil 请注意:此命令的语法在最新的 PowerShell 版本中已更改。如果您想尽快更新,请记住这一点,因为您必须更改脚本:docs.microsoft.com/en-us/powershell/module/psreadline/…
    • 好的,我会检查的。再次感谢!
    猜你喜欢
    • 2010-10-06
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    • 2014-06-28
    • 1970-01-01
    相关资源
    最近更新 更多