1

I have a folder with files. I need to filter according to an extension and to ZIP one by one

$files = Get-ChildItem -path "C:\Temp\SharedFolder\SideVIP\*" -Filter *.VIP
foreach ($file in $files) {

Need some help with the rest

2 Answers 2

3

In PowerShell 4+, you can use Compress-Archive

$destPath = 'X:\NewPath'
foreach($file in $files) {
  Compress-Archive -Path $file -DestinationPath "$destPath\$($file.BaseName).zip" 
}

And if you need to "unzip":

$files = Get-ChildItem C:\Temp\SharedFolder\SideVIP\*.zip
foreach($file in $files) { Expand-Archive -Path $file -DestinationPath . -Force }
Sign up to request clarification or add additional context in comments.

8 Comments

Nice. Small caveat: While the use of a wildcard-based input path in this case results in the $file instances stringifying to their full path, that isn't always the case in Windows PowerShell (it now is in PowerShell (Core) 7+), so it is safer to use $file.FullName explicitly.
This script was tested on PowerShell 5.1. If you have 6 or 7 and it doesn't work, I would definitly use $file.FullName. But I would be sad to know that Microsoft's own function could not handle an object.
Yes, as I said it works in this case, because you're using a wildcard path directly as the -Path argument. But - in Windows PowerShell - the seemingly equivalent Get-ChildItem C:\Temp\SharedFolder\SideVIP -Filter *.zip would not work. This headache has gone away in PowerShell Core (v6+). See this answer for details.. Yes, it is sad that PowerShell's cmdlets stringify [System.IO.FileInfo] instances instead of using them as-is, as objects.
Sorry, posted the wrong link: see this answer for an explanation of the inconsistent stringification of [System.IO.FileInfo] and [System.IO.DirectoryInfo] instances in Windows PowerShell.
After all the files were compressed I need to copy them to another folder. There is an easy way?
|
-2

Creating zip file using Power shell. first need to install 7Zip software

function create-7zip([String] $aDirectory, [String] $aZipfile){
    [string]$pathToZipExe = "$($Env:ProgramFiles)\7-Zip\7z.exe";
    [Array]$arguments = "a", "-tzip", "$aZipfile", "$aDirectory", "-r";
    & $pathToZipExe $arguments;
}

Remove-item C:\BackupDummy\*.zip
Get-ChildItem C:\Satwadhir\ | 
    Group-Object -Property { $_.Name.Substring(0, $_.Name.Length) } |
    % { create-7zip $_.Group.FullName "C:\BackupDummy\$($_.Name).zip" }

2 Comments

First need to install 7Zip software
I downvoted this as it suggests the installation of a third-party archiving library which is not required, this can be achieved using the Compress-Archive in Powershell, and the OP asked about "Using PowerShell to Create Zip Files"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.