Powershell – Invoke-Expression with exe in Program Files

7zippowershell

I'm trying to run a Powershell command to call 7-Zip to zip up a folder using the following command:

$command = $SevenZip + " a " + $targetDirForZip + $GetDateName + "_" + $dir.Name + ".7z " + $dir.FullName
Invoke-Expression $command

The variables being fed into $command are already set and $SevenZip is "c:\Program Files\7-Zip\7z.exe"

This isn't working and I'm trying to work out the best way to call 7-Zip from Powershell. Ideas?

Best Answer

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.