powershell - 使用脚本中的参数执行 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
我做错了什么?
解决方案
您将所有参数作为单个字符串传递,这不是您想要的。
你想做的事情叫做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"
推荐阅读
- firebase - 添加了新项目的 Firestore 实时分页
- c++ - SQL Server - 未找到数据源名称且未指定默认驱动程序
- java - 片段错误android
- java - 使用格式错误的 url 下载图像
- javascript - Node.JS Schema.pre('save) 没有改变数据
- ios - YouTube Data Api Swift:通过隐私状态和标签将视频分享到 YouTube
- php - 获取非英文字符的单词首字母
- javascript - 从表中的对象数组返回键对值
- json.net - 我删除了 Netwonsoft.json 的所有实例,现在我的 TFS 2017 构建代理失败 - 我该如何取回它?
- acumatica - 扩展 JAMS 制造逻辑会给出消息“尝试通过方法访问 'PX.Data.PXGraphExtension`1
..ctor()' 失败