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.
Resources
- Running a Command line script from within powershell
- invoke-expression with .exe that has spaces in its path




September 14th, 2009 at 8:21 am
Thanks for that one. I have been struggling with a command with spaces, and parameters that use hyphens rather than dashes. So my command variable looked like $_cmd = “‘.\My File.cmd’ -i foo -o foo2″, and this would not work with Invoke-Expression. Without the quotes around the command, I would get one error, and with the quotes, it gets confused with the -, where is assumes it is an operator. Putting the & in the command has fixed it for me, $_cmd = “& ‘.\My File.cmd’ -i foo -o foo2″. This slight change on the command execution is not well published on the Internet, as I have been searching for a fix for the last week. I was ready to give up on this learning exercise and go back to vbs. Thanks again.