调用调用-表达的参数在PowerShell中 [英] calling Invoke-Expression with Parameters in Powershell
问题描述
我已经写在C#的PowerShell模块,有一堆的cmdlet像
I've written a powershell module in c# that has a bunch of cmdlets like
添加-VM
的cmdlet接触到的API,并提取数据回来。
The cmdlets reach out to an API and pull data back.
但统一起见与产品的SSH CLI,我写了一个调用的函数newtask接受addvm作为一个参数和的$ args。
but for the sake of uniformity with the ssh CLI of the product, i've written a function called newtask that accepts 'addvm' as an argument and $args.
例如:
newtask addvm -id 12345
我然后调用添加-VM,并传递的$ args作为字符串像这样
I then invoke Add-VM and pass $args as a string like so
Invoke-Expression Add-VM $argstr
的问题是,添加虚拟机抛出一个错误,它无法找到接受参数System.Object的[]
The problem is that Add-VM throws an error that it cannot find a positional parameter that accepts argument System.Object[]
一个位置参数无法找到接受参数'System.Object的[]
A positional parameter cannot be found that accepts argument 'System.Object[]'
虽然我可以很容易别名'addvm'到'添加虚拟机,我试图保持与SSH CLI均匀性,使新用户能够迅速开始利用这个模块。
While I could easily alias 'addvm' to 'Add-VM', i'm trying to maintain uniformity with the ssh CLI so that new users can quickly start utilizing this module.
我想,发送一个字符串,如-id 12345'就足够了,但事实并非如此。是否pscmdlet期望获得什么东西?
I figured that sending a string like '-id 12345' would suffice but it's not. Does the pscmdlet expect to receive something else?
在此先感谢。
推荐答案
这是错误来自调用,表达不添加虚拟机,你只需要大约参数报价:
That error is from Invoke-Expression not Add-VM and you just need quotes around the argument:
Invoke-Expression "Add-VM $argstr"
这具有迫使所有对象为字符串格式的缺点。这可能是简单的类型,如整型和字符串可以接受的,但如果你想通过一个更复杂的对象,它不会工作。另一种方法是,以图示与 @args
的论点,但我不认为你可以通过调用-表达做到这一点或调用命令。您需要直接调用该cmdlet:
This has the drawback of forcing all objects into string format. This might be acceptable for simple types like ints and strings but if you want to pass through a more complex object it won't work. An alternative would be to splat the arguments with @args
but I don't think you can do this through Invoke-Expression or Invoke-Command. You need to directly call the cmdlet:
function newtask {
params([string]$command)
switch ($command) {
"addvm" { Add-VM @args }
"deletevm" { Remove-VM @args }
}
}
这篇关于调用调用-表达的参数在PowerShell中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!