I'm using the next code to download some zip archive:
$client = new-object System.Net.WebClient
$client.DownloadFile("https://chromedriver.storage.googleapis.com/$LatestChromeRelease/chromedriver_win32.zip","D:\MyFolder.zip")
As the result I get the ZIP archive "MyFolder.zip" that contains a required file (lets imagine 'test.txt').
How I can extract this particular file from the ZIP archive into a given folder?
PowerShell 4+ has an
Expand-Archivecommand but as of PS 7.2.3 it can only extract the archive completely. So extract it to a temporary directory and copy the file you are interested in.If you have PS 5.1+ available, scroll down for a more efficient solution that uses .NET classes.
With PS 5.1+ you can use .NET classes to directly extract a single file (without having to extract the whole archive):
Notes:
Convert-Pathshould be used when passing PowerShell paths that might be relative paths, to .NET APIs. The .NET framework has its own current directory, which doesn't necessarily match PowerShell's. UsingConvert-Pathwe convert to absolute paths so the current directory of .NET is no longer relevant..Whereand.ForEachare PowerShell intrinsic methods that are available on all objects. They are similar to theWhere-ObjectandForEach-Objectcommands but more efficient. Passing'First'as the 2nd argument to.Wherestops searching as soon as we have found the file..Wherealways outputs a collection, even if only a single element matches. This is contrary toWhere-Objectwhich returns a single object if only a single element matches. So we have to write$foundFile[ 0 ]when passing it to functionExtractToFile, instead of just$foundFilewhich would be an array.