Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell script to download a zip file and unzip it

I need some help in putting my thoughts together in a working code.

This is what I have:

1st Step: I am getting the FTP user name and password as params.

param(#define parameters
[Parameter(Position=0,Mandatory=$true)]
    [string]$FTPUser
[Parameter(Position=1,Mandatory=$true)]
    [string]$FTPPassword    
[Parameter(Position=2,Mandatory=$true)]
    [string]$Version    
)

I then set these variables:

$FTPServer = "ftp.servername.com"
$SetType = "bin"

Now, I want to establish a connection. I Google'd for Syntax and found this. Not sure if this will establish a FTP connection. I am yet to test,

$webclient = New-Object System.Net.WebClient 
    $webclient.Credentials = New-Object System.Net.NetworkCredential($FTPUser,$FTPPassword) 

This is the part I do not know how to code:

$Version is one of my input parameter. I have a zip file in FTP as:

ftp.servername.com\builds\my builds\$Version\Client\Client.zip

I want to download that Client.zip into my local machine's (where the script is run from) "C:\myApp\$Version" folder. So, the FTP download will create a new sub-folder with the $version name with in C:\myApp for every run.

Once this is done, I also need to know how to unzip this client.zip file under C:\myApp\$Version\Client\<content of the zip file will be here>

like image 731
Bhavani Kannan Avatar asked Jan 27 '17 14:01

Bhavani Kannan


People also ask

How do I unzip a ZIP file in PowerShell?

To unzip a file using PowerShell, you can utilize the “Expand-Archive” command. The Expand-Archive command unzips or extracts the content of a zipped or archived file to its destination folder.

How do I download and unzip a ZIP file?

Right-click the file you want to zip, and then select Send to > Compressed (zipped) folder. Open File Explorer and find the zipped folder. To unzip the entire folder, right-click to select Extract All, and then follow the instructions. To unzip a single file or folder, double-click the zipped folder to open it.


2 Answers

You may use the Expand-Archive cmdlet. They are available in Powershell version 5. Not sure with previous versions. See syntax below:

Expand-Archive $zipFile -DestinationPath $targetDir -Force

The -Force parameter will force to overwrite the files in target directory if it exists.

With your parameters, it will look like this:

Expand-Archive "C:\myApp\$Version\Client.zip" -DestinationPath "C:\myApp\$Version" -Force

like image 108
alltej Avatar answered Oct 13 '22 13:10

alltej


Add-Type -assembly "System.IO.Compression.Filesystem";
[String]$Source = #pathA ;
[String]$Destination = #pathB ;
[IO.Compression.Zipfile]::ExtractToDirectory($Source, $Destination);

or

[IO.Compression.Zipfile]::CreateFromDirectory($Source,$Destination);

Depending on if you are trying to zip OR unzip.

like image 27
Nicholas Jacquet Avatar answered Oct 13 '22 12:10

Nicholas Jacquet