Invoking files with spaces in PowerShell
I needed to run an executable multiple times with different parameters and felt that it would be easier to write the script in PowerShell than in a command script. The biggest challenge I ran into was running the executable because the path to it has spaces in it (C:\Program Files\etc). Add to that I wanted to put the whole command in a string first and then invoke the string and this turned out to be a lot more challenging than I had hoped.
To invoke an executable (or any file, for that matter) that has spaces in it, you need to use quotes and then use the ampersand (&) operator. For example, if you want to invoke a file called C:\My File.cmd, you would have to invoke it like so:
& '.\My File.cmd'
If you wanted to pass parameters, you would do this:
& '.\My File.cmd' foo
So far so good. Things are a bit different, however, if you want to invoke a command in a variable. To do that, you must use the Invoke-Expression cmdlet, like so:
$_cmd = "'.\My File.cmd' foo" Invoke-Expression "& $_cmd"
or
$_cmd = "& '.\My File.cmd' foo" Invoke-Expression $_cmd
PowerShell is certainly powerful, but this was far from obvious. Fortunately there are others who have posted about this. You can check out the resources I’ve listed below for a couple webpages that helped me.




