- 1 year ago
Archive all files of a certain type recursively from powershell
Comment
1 / 1
To archive all files of a certain type recursively from PowerShell, you can use the Compress-Archive
cmdlet along with the Get-ChildItem
cmdlet. The Compress-Archive
cmdlet creates a zip archive, and the Get-ChildItem
cmdlet retrieves the files of the specified type.
Here's an example of how to archive all .txt
files from a specific directory and its subdirectories:
powershell# Replace 'C:\Your\Directory' with the path to your target directory
$sourceDirectory = "C:\Your\Directory"
$destinationArchive = "C:\Your\Archive.zip"
# Use Get-ChildItem to retrieve all .txt files recursively
$filesToArchive = Get-ChildItem -Path $sourceDirectory -Recurse -Filter "*.txt" -File
# Check if any files were found
if ($filesToArchive.Count -gt 0) {
# Create the zip archive
Compress-Archive -Path $filesToArchive.FullName -DestinationPath $destinationArchive
Write-Host "Archive created successfully."
} else {
Write-Host "No .txt files found to archive."
}
Explanation:
- Replace
'C:\Your\Directory'
with the path to your target directory. - The
-Recurse
parameter forGet-ChildItem
ensures that files are retrieved recursively from all subdirectories. - The
-Filter "*.txt"
parameter specifies that only files with the.txt
extension should be selected. - The
-File
parameter ensures that only files (not directories) are selected. - The selected files are then passed to
Compress-Archive
, which creates the zip archive at the specified destination.
After running the script, you will have a zip archive named Archive.zip
in the specified destination folder, containing all the .txt
files from the source directory and its subdirectories. If no .txt
files are found, the script will output a message indicating that no files were archived.