14

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?

7 Answers 7

26

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.

0
7

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
5

I ran into this problem as well, here was my solution.

invoke-expression "& 'C:\Program Files\CIESetupClient\Staging\ffd4bc34-52c1-43e7-92d4-93d2f59d7f52\vstor_redist.exe' /q /norestart /log c:\Logs\VSTOR_Redist.log "

i was able to leave my paramaters outside the single quotes pointing to my exe, i think this is probably the easiest way to call an exe with parameters using invoke-expression.

0
4

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..."
1

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.

0
0

Works for me:

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

Write-Host "Running: $command"

Invoke-Expression $command
0

You can also use MS-DOS commands from within a Windows PowerShell script.

I've always loved CMD.exe's START command, which allows you to start an command in parallel.

So to start your 7-zip, put the following command in your Powershell script:

    cmd.exe /c start <your 7-zip command like in MS-DOS> 
1
  • this answer doesn't help anyhow to resolve the problem May 25, 2015 at 6:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.