Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing external command from PowerShell is not accepting a parameter

Tags:

powershell

I am executing the following code attempting to execute the 7z.exe command to unzip files.

$dir contains the user input of the path to the zip file which can contain spaces of course! And $dir\temp2 below is a directory that I previously created.

Get-ChildItem -path $dir -Filter *.zip |
ForEach-Object {
    $zip_path = """" + $dir + "\" + $_.name + """"
    $output = " -o""$dir\temp2"""
    &7z e $zip_path $output
}

When I execute it I get the following from 7z.exe:

7-Zip [64] 9.20  Copyright (c) 1999-2010 Igor Pavlov  2010-11-18

Processing archive: C:\test dir\test.zip


No files to process

Files: 0
Size:       0
Compressed: 50219965

If I then copy the value from $zip_path and $output to form my own cmd line it works!

For example:

7z e "c:\test dir\test.zip" -o"c:\test output"

Now, I can reproduce the same message "no files to process" I get when I execute within PowerShell by using the following cmd in cli.

7z e "c:\test dir\test.zip" o"c:\test output"

So, it seems that PowerShell is removing the dash char from my -o option. And yes, it needs to be -o"C:\test output" and not -o "c:\test output" with 7z.exe there is no space between the -o parameter and its value.

I am stumped. Am I doing something wrong or should I be doing this a different way?

like image 468
john johnson Avatar asked Jul 06 '26 08:07

john johnson


1 Answers

I can never get Invoke-Expression (alias = &) to work right either, so I learned how to use a process object

    $7ZExe = (Get-Command -CommandType Application  -Name 7z )
    $7ZArgs = @(
        ('-o"{0}\{1}"' -f $dir, $_.Name), 
        ('"{0}\{1}"' -f $dir, 'temp2')
    )

    [Diagnostics.ProcessStartInfo]$7Zpsi = New-Object -TypeName:System.Diagnostics.ProcessStartInfo -Property:@{
        CreateNoWindow = $false;
        UseShellExecute = $false;
        Filename = $7ZExe.Path;
        Arguments = $7ZArgs;
        WindowStyle = 'Hidden';
        RedirectStandardOutput = $true
        RedirectStandardError = $true
        WorkingDirectory = $(Get-Location).Path
    }

    $proc = [System.Diagnostics.Process]::Start($7zpsi)
    $7ZOut = $proc.StandardOutput
    $7ZErr = $proc.StandardError
    $proc.WaitForExit()
like image 134
Eris Avatar answered Jul 08 '26 20:07

Eris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!