calling Invoke-Expression with Parameters in Powershell calling Invoke-Expression with Parameters in Powershell powershell powershell

calling Invoke-Expression with Parameters in Powershell


I know this is a little old now, but I was having a similar issue and a co-worker showed me that escaping $argstr prevents the object from getting converted to a string.

Invoke-Expression "Add-VM `$argstr"


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

Invoke-Expression "Add-VM $argstr"

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 }    }}