BP PS
BP PS

Reputation: 13

Zipping folders using a Powershell script

Wrote the following code to move files to a specific Year-Month folder on a drive. However, I would also like to zip the folder I wrote to at the end of the operation. How do I do that?

# Get the files which should be moved, without folders
$files = Get-ChildItem 'D:\NTPolling\InBound\Archive' -Recurse | where {!$_.PsIsContainer}

# List Files which will be moved
# $files

# Target Filder where files should be moved to. The script will automatically create a folder for the year and month.
$targetPath = 'D:\SalesXMLBackup'

foreach ($file in $files)
{
# Get year and Month of the file
# I used LastWriteTime since this are synced files and the creation day will be the date when it was synced
$year = $file.LastWriteTime.Year.ToString()
$month = $file.LastWriteTime.Month.ToString()

# Out FileName, year and month
$file.Name
$year
$month

# Set Directory Path
$Directory = $targetPath + "\" + $year + "\" + $month
# Create directory if it doesn't exsist
if (!(Test-Path $Directory))
{
New-Item $directory -type directory
}

# Move File to new location
$file | Move-Item -Destination $Directory
}

The intention is to move these files into a folder and zip them and archive them for later use. So I will schedule this once a month to run for the previous month

Upvotes: 1

Views: 1198

Answers (2)

henrycarteruk
henrycarteruk

Reputation: 13217

If you're using PowerShell v5 then you can use the Compress-Archive function:

Get-ChildItem $targetPath | Compress-Archive -DestinationPath "$targetPath.zip"

This will compress D:\SalesXMLBackup to D:\SalesXMLBackup.zip

Upvotes: 2

RadFox
RadFox

Reputation: 419

This is the code I am using for unzipping all the files in a directory. You just need to modify it enough to zip instead of unzipping.

$ZipReNameExtract = Start-Job {
#Ingoring the directories that a search is not require to check
$ignore = @("Tests\","Old_Tests\")

#Don't include "\" at the end of $loc - it will stop the script from matching first-level subfolders
 $Files=gci $NewSource -Fecurse | Where {$_.Extension -Match "zip" -And $_.FullName -Notlike $Ignore} 
    Foreach ($File in $Files) {
        $NewSource = $File.FullName
        #Join-Path is a standard Powershell cmdLet
        $Destination = Join-Path (Split-Path -parent $File.FullName) $File.BaseName
        Write-Host -Fore Green $Destination
        #Start-Process needs the path to the exe and then the arguments passed seperately. 
        Start-Process -FilePath "C:\Program Files\7-Zip\7z.exe" -ArgumentList "x -y -o $NewSource $Destination" -Wait
    }
}
Wait-Job $ZipReNameExtract
Receive-Job $ZipReNameExtract

Let me know if it helps.

The UnderDog...

Upvotes: 0

Related Questions