Invoke-Expression with exe in Program Files Invoke-Expression with exe in Program Files powershell powershell

Invoke-Expression with exe in Program Files


I've had the same problem before. This is code (almost) straight from a backup script that I use currently:

[string]$pathToZipExe = "C:\Program Files\7-zip\7z.exe";[Array]$arguments = "a", "-tgzip", $outputFilePath, $inputFilePath;& $pathToZipExe $arguments;

I've gotten into the habit of using an argument array with the call operator, It seems to be more robust than other methods.


You don't need to use Invoke-Expression just use the invocation (call) operator & to invoke a string that names a command to execute. Note that you want to keep the parameters separate in this case i.e. the string SevenZip should just be the path to the EXE e.g.:

&$SevenZip a "$targetDirForZip$GetDateName_$($dir.Name).7z" $dir.FullName


You actually don't need Invoke-Expression. You can simply invoke the command by using the ampersand such as:

&$Command

But there's also the Start-Process cmdlet which might be better suited for what you're trying to do. By executing the command as a string above, you're prone to errors if the $SevenZip contains spaces and is not quoted. Instead I would use:

Start-Process $SevenZip "...rest..."