I have a folder with several subfolders in it. Each subfolder may/may not contain some *.ZIP files.
I am trying to extract each zip file in a separate folder with the same name as the original zip file (overwrite the folder if exists) and then delete the archive afterwards.
But what I get from the code below, is the extraction of all ZIP files in the parent directory which is not I want.
Here is my code:
foreach ($file in (dir -recurse *.zip)) { & "c:\Program Files\7-zip\7z" x "$file" -aoa }; rm dir -recurse *.zip
Can someone help me with this please?
I just found the perfect answer to my question and I am willing to post it here for anyone who comes across this thread in future.
I had couple of issues. One of which was dealing with long paths in PowerShell (v5.1 Windows 10). To circumvent that, the user should install and load PSAlphaFS
module in PowerShell and use Get-LongChildItem
instead of Get-ChildItem
. To do that, first you need to run following command to update the PowerShell execution policy on the system :
Set-ExecutionPolicy RemoteSigned
Next, you need to install the module by this one:
Install-Module -Name PSAlphaFS
And finally to load it with this one:
import-module PSAlphaFS
Now we are ready to rock and role. Simply paste following code into PowerShell and it should do the job. (remember to change the path in line 20)
Add-Type -AssemblyName System.IO.Compression.FileSystem
function Unzip
{
param([string]$zipfile, [string]$outpath)
try {
[IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)
echo "Done with unzip of file :) "
$true
}
catch {
echo "Oops....Can't unzip the file"
$false
}
}
$flag = $true
while($flag)
{
$zipFiles = Get-LongChildItem -Path "c:\Downloads\New Folder\FI" -Recurse | Where-Object {$_.Name -like "*.zip"}
if($zipFiles.count -eq 0)
{
$flag = $false
}
elseif($zipFiles.count -gt 0)
{
foreach($zipFile in $zipFiles)
{
#create the new name without .zip
$newName = $zipFile.FullName.Replace(".zip", "")
if(Unzip $zipFile.FullName $newName){
Remove-Item $zipFile.FullName
}
}
}
Clear-Variable zipFiles
}