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!”
}