views:

220

answers:

4

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?

+2  A: 

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..."
Josh Einstein
+1  A: 

Let me guess, it's trying to invoke "c:\Program"?

Not sure of the correct syntax for PS, but you'll need to do something about that space.

Anon.
Correct - that's exactly what it's trying to do...
Guy
+1  A: 

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
Keith Hill
+2  A: 

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.

Tom