1

I want to extract a zip file in Downloads folder to Desktop using PowerShell and C#.

I need it to work with Windows 7, 8, & 10.


I'm trying to take these PowerShell commands

 

$shell = New-Object -ComObject shell.application
$zip = $shell.NameSpace("zip file path")
foreach ($item in $zip.items()) {
    $shell.Namespace("unzip destination path").CopyHere($item)
}

And run it through a C# Process.Start()

Process.Start("powershell.exe",
    "timeout 3; "
    + "$shell = New-Object -ComObject shell.application; "
    + "$zip = $shell.NameSpace(\"C:\\Users\\Matt\\Downloads\\MyFile.zip\"); "
    + "foreach ($item in $zip.items()) {$shell.Namespace(\"C:\\Users\\Matt\\Desktop\\\").CopyHere($item, 0x14)}"
);

Problem

PowerShell launches but fails to extract, and closes out before I can read the error.

However, if I copy paste those chained commands into PowerShell without C#, it works.

$shell = New-Object -ComObject shell.application; $zip = $shell.NameSpace('C:\Users\Matt\Downloads\MyFile.zip'); foreach ($item in $zip.items()) {$shell.Namespace('C:\Users\Matt\Desktop\').CopyHere($item, 0x14)}

This works but it's for PowerShell 5 only.

Process.Start("powershell.exe",
    "timeout 3; Expand-Archive 'C:\\Users\\Matt\\Downloads\\MyFile.zip' -Force -DestinationPath 'C:\\Users\\Matt\\Desktop\\'"
);
Matt McManis
  • 4,475
  • 5
  • 38
  • 93

1 Answers1

1

I may have solved it while writing out the question and refactoring other chained commands.

I found this article and combined it with the other code.
https://www.howtogeek.com/tips/how-to-extract-zip-files-using-powershell/

Process.Start("powershell.exe",
    "-nologo -noprofile -command "
    + "timeout 3; "
    + "$shell = new-object -com shell.application; "
    + "$zip = $shell.NameSpace('C:\\Users\\Matt\\Downloads\\MyFile.zip'); "
    + "foreach ($item in $zip.items()) {$shell.Namespace('C:\\Users\\Matt\\Desktop\\').CopyHere($item, 0x14)}"
);

The differences are:

adding -nologo -noprofile -command
-com instead of -ComObject
single quotes ' instead of double " around paths.
And chaining messages with Write-Host \"hello\" -NoNewLine instead of echo.

Matt McManis
  • 4,475
  • 5
  • 38
  • 93