Skip to content

Instantly share code, notes, and snippets.

@crazy4groovy
Last active March 11, 2023 06:03
Show Gist options
  • Save crazy4groovy/0344d3b2f2397cce23bdf85fdddf6259 to your computer and use it in GitHub Desktop.
Save crazy4groovy/0344d3b2f2397cce23bdf85fdddf6259 to your computer and use it in GitHub Desktop.
various mass file manipulation scripts (PowerShell)
## Move files from a large-sized folder into smaller-sized subfolders
# Define variables
$sourceFolder = "C:\Path\To\SrcFolder"
$destinationFolder = "C:\Path\To\DestFolder"
$batchSize = 10000
$folderCounter = 1
# Create new subfolder in destination folder
$folderName = $folderCounter.ToString().PadLeft(4, '0')
$folderPath = Join-Path $destinationFolder $folderName
New-Item -ItemType Directory -Force -Path $folderPath
# Loop through files in source folder
$counter = 0
Get-ChildItem $sourceFolder -File | ForEach-Object {
# Move file to new subfolder
$destination = Join-Path $folderPath $_.Name
Move-Item $_.FullName $destination -Force
# Increment counter
$counter++
# Create new subfolder if batch size is reached
if ($counter -eq $batchSize) {
$counter = 0
$folderCounter++
$folderName = $folderCounter.ToString().PadLeft(4, '0')
$folderPath = Join-Path $destinationFolder $folderName
New-Item -ItemType Directory -Force -Path $folderPath
}
}
# Define variables
$folderPath = ".\imgs"
$textToMatch = "some part of text"
# Find recursively and delete each file one-at-a-time
Get-ChildItem $folderPath -Recurse -File | Where-Object { $_.Name -like "*$textToMatch*" } | ForEach-Object {
Write-Host $_.FullName
Remove-Item $_.FullName -Force
}
# Define variables
$folderPath = "C:\Path\To\Folder"
$patternToMatch = "pattern to match"
$newFileName = "new file name"
# Find and rename each file that matches the pattern
Get-ChildItem -Path $folderPath -Recurse -File | Where-Object { $_.Name -match $patternToMatch } | ForEach-Object {
$newName = $_.Name -replace $patternToMatch, $newFileName
$newPath = Join-Path -Path $_.Directory.FullName -ChildPath $newName
Write-Host $_.FullName $newName
Rename-Item -Path $_.FullName -NewName $newName
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment