Author Posts

June 8, 2016 at 4:05 am

How to write powershell script to archive folders only when the folder has files of certain type for instance (.txt, .csv, .xls, .xlsx). My source path is "C:\Temp\Test\" and there are 5 sub-folders

foldera
folderb
folderc
folderd
foldere
Archive

Only foldera, folderb, folderc have the files to be archived, the archive path is "C:\Temp\Test\Archive" and this has folders foldera, folderb so these folders need not be created but files need to be zipped and copied, folderc needs to be created and the files have to be zipped and copied.

Using the code below I get the files but not the folder that particular file was in. I am able to create the folders but get error if the folder already exists and if I just copy-item I can move just the files but cannot create the folder. Please guide me.

​$source = "C:\Temp\"

$archive = "C:\Temp\Archive"

$archive = Get-ChildItem -Recurse -Path $source -include *.txt, *.csv, *.xls| select directory | sort -Unique -Property Directory | Select -expand Directory | Copy-Item -Destination $archive

If (!(Test-Path $archive)) {

Get-ChildItem -Recurse -Path $source -include *.txt, *.csv, *.xls | select directory | sort -Unique -Property Directory | Select -expand Directory | Copy-Item -Destination $archive

}

else {

Write-Host "Directory $archive already exists!"

}​

June 8, 2016 at 3:20 pm

This will display files as they are added to zip files. If you want to learn more about adding to zip files using .NET and PowerShell, check the link.
https://mcpmag.com/articles/2014/09/29/file-frontier-part-6.aspx

$source = "C:\Temp\"
$dest = "C:\Temp\Archive"
$files = Get-ChildItem -Path $source -Recurse -Exclude Archive -Include '*.txt','*.csv','*.xls'
Add-Type -assembly 'system.io.compression.filesystem'

foreach ($file in $files){
$folder = $file.directoryname | Split-Path -Leaf

# Create zip
If (!(Test-Path $dest$folder.zip)){New-Item $dest$folder.zip -ItemType file}

# Add files to zip
$zip = [io.compression.zipfile]::Open("$dest$folder.zip",'Update')
[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,$file.FullName,$file.name)
$zip.dispose()
}

# Results
# Archive\foldera.zip    
# Archive\folderb.zip

June 10, 2016 at 4:56 am

Thanks very much.