如何使用PowerShell变量作为命令参数?
我正在尝试使用变量作为命令的参数,但不太明白。假设 MyCommand
将接受两个参数:option1
和 option2
并且它们接受布尔值。我如何使用 $newVar 来替换选项 1 或 2?例如:
$newVar = "option1"
MyCommand -$newVar:$true
我不断得到类似'无法找到接受参数'-System.String option1'的位置参数的信息。
更具体地说:
此处,CSV 文件是不同策略的输出。该循环遍历文件中的每个属性,并在我的策略 asdf 中设置该值;因此 -$_.name:$_.value
应替换为 -AllowBluetooth:true
。
Import-Csv $file | foreach-object {
$_.psobject.properties | where-object {
# for testing I'm limiting this to 'AllowBluetooth' option
if($_.name -eq "AllowBluetooth"){
Set-ActiveSyncMailboxPolicy -Identity "asdf" -$_.name:$_.value
}}
}
I'm trying to use a variable as a command's parameter but can't quite figure it out. Let's say MyCommand
will accept two parameters: option1
and option2
and they accept boolean values. How would I use $newVar to substitute option 1 or 2? For example:
$newVar = "option1"
MyCommand -$newVar:$true
I keep getting something along the lines of 'A positional parameter cannot be found that accepts argument '-System.String option1'.
More Specifically:
Here, the CSV file is an output of a different policy. The loop goes through each property in the file and sets that value in my policy asdf; so -$_.name:$_.value
should substitute as -AllowBluetooth:true
.
Import-Csv $file | foreach-object {
$_.psobject.properties | where-object {
# for testing I'm limiting this to 'AllowBluetooth' option
if($_.name -eq "AllowBluetooth"){
Set-ActiveSyncMailboxPolicy -Identity "asdf" -$_.name:$_.value
}}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
通常,要使用变量填充 cmdlet 参数,您可以使用哈希表变量,并使用 @
添加示例:
Typically to use a variable to populate cmdlet parameters, you'd use a hash table variable, and splat it, using @
Added example:
看看这是否适合您:
See if this works for you:
我遇到了同样的问题,刚刚找到解决方法。解决方案是使用 invoke-Expression:invoke-Expression $mycmd
这使用 $mycmd-string,替换变量并将其作为具有给定参数的 cmdlet 执行
I had the same Problem and just found out how to resolve it. Solution is to use invoke-Expression: invoke-Expression $mycmd
This uses the $mycmd-string, replaces variables and executes it as cmdlet with given parameters
如今,如果您不介意将字符串作为命令进行计算,则可以使用
Invoke-Expression
:Nowadays, If you don't mind evaluating strings as commands, you may use
Invoke-Expression
:我会尝试使用:
result
无法工作,因为 & 运算符仅执行单个命令,而无需参数或脚本块。
I would try with:
result
Can't work because the ampersand operator just execute single commands without prameters, or script blocks.