Resolved: PowerShell, getting string syntax correct in 7-zip script

In this post, we will see how to resolve PowerShell, getting string syntax correct in 7-zip script


I can’t seem to solve this, been struggling with it for a while (maybe it’s simple; I just can’t see it as I’ve been looking at it for so long). I can get the 7z.exe syntax to work, but when I try and put it together into a simple script, it fails.
e.g., if I run .\zip.ps1 "C:\test\" "C:\test\test1.txt" "C:\test\test2.txt*
Instead of zipping up the 2 files required, it zips up everything in the C:\test folder, completely ignoring my arguments.
How can I adjust the below string syntax so that 7z.exe will correctly respect the input arguments and compress them from within a PowerShell script?
The error that I get is:

Best Answer:

Pass $args directly to your & "$sevenzip" call:
This makes PowerShell pass the array elements as individual arguments, automatically enclosing them in "..." if needed (based on whether they contain spaces).
Using arrays as arguments for external programs is in effect an implicit form of array-based splatting; thus, you could alternatively pass @args.
Generally, note that in direct invocation[1] you cannot pass multiple arguments to an external program via a single string; that is, something like "$args_line" cannot be expected to work, because it is passed as a single argument to the target program.
If you want to emulate the resulting part of the command line, for display purposes:
  • Each argument is conditionally enclosed in "..." – namely based on whether it contains at least one space – and the resulting tokens are joined to form a single, space-separated list (string).
  • The assumption is that no argument has embedded " chars.

A simplified example:
Note: Write-Output is used in lieu of an external program for convenience. Technically, you’d have to use @args instead of $args in order to pass the array elements as individual, positional arguments, but, as stated, this is the default behavior with externals programs. Write-Output, as a PowerShell-native command, receives the array as a whole, as a single argument when $args is used; it just so happens to process that array the same way as if its elements had been passed as individual arguments.
[1] You can use a single string as an -ArgumentList value for Start-Process. However, Start-Process is usually the wrong tool for invoking console applications such as 7z.exe – see this answer.

If you have better answer, please add a comment about this, thank you!