Invoke-Expression call with parameters in Powershell

I wrote a powershell module in C # that has a bunch of cmdlets like

Add VM

Cmdlets access the API and return data.

but for uniformity with the ssh CLI of the product, I wrote a newtask function that takes "addvm" as an argument and $ args.

eg

newtask addvm -id 12345 

Then I call Add-VM and pass $ args as a string like

 Invoke-Expression Add-VM $argstr 

The problem is that Add-VM throws an error that it cannot find the positional parameter that takes the argument System.Object []

Cannot find positional parameter that takes argument 'System.Object []'

While I could easily add "addvm" to the "Add-VM", I'm trying to maintain consistency with the ssh CLI so that new users can quickly start using this module.

I decided that sending a string like '-id 12345' would be sufficient, but it is not. Does pscmdlet expect anything else?

Thanks in advance.

+6
source share
2 answers

This error is from Invoke-Expression, not Add-VM, and you just need quotes around the argument:

 Invoke-Expression "Add-VM $argstr" 

This has the disadvantage of forcing all objects into a string format. This may be acceptable for simple types such as ints and strings, but if you want to go through a more complex object, this will not work. An alternative would be to split the arguments with @args , but I don't think you can do this via 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 } } } 
+3
source

I know this is a bit old-fashioned now, but I had a similar problem, and an employee showed me that escaping $ argstr prevents the object from being converted to a string.

 Invoke-Expression "Add-VM `$argstr" 
+1
source

Source: https://habr.com/ru/post/977372/


All Articles