I have written a script to convert and resize pictures for a project. It converts and resizes for the directory set, but I also want to cover the files in the subdirectorys. How could I let this script run for all subdirectorys in the chosen directory?
$refdate = (Get-Date).AddDays(-1).Date
$dir = "DIRECTORY"
<# Converting .jpg to .webp #>
<# Deletes all .webp files of recently changed .jpg files #>
$jpegs = (Get-ChildItem -Path $dir -Filter '*.jpg' -File | Where-Object { $_.CreationTime -gt $refdate }).BaseName
Get-ChildItem -Path $dir -Filter '*.webp' -File | Where-Object { $jpegs -contains $_.BaseName } | Remove-Item
<# Creates .webp files for all .jpg files in the directory that don't have a corresponding .jpg file #>
$images = Get-ChildItem -File $dir*.jpg, $dir*.webp |
Group-Object { $_.BaseName } |
Where-Object { $_.Group.Extension -notcontains '.webp' } |
ForEach-Object Group
foreach ($img in $images) {
$outputName = $img.DirectoryName + "" + $img.BaseName + ".webp"
cwebp.exe $img.Fullname -o $outputName
}
<# Generating thumbnails
<# Removes all thumbnails from .webp images that have been edited in the last 24 hours #>
Get-ChildItem $dir*.webp -Exclude *-thumb.webp -File |
Where-Object CreationTime -gt $refdate |
ForEach-Object { $_.Fullname -replace '.webp$', '-thumb.webp' } | Remove-Item
<# Generates resized thumbnail based on if a .webp has already been resized #>
$width = 145
$heigth = 204
$voorbeeld = Get-ChildItem -File $dir*.webp |
Where-Object {$_.Name -notmatch "-thumb" -and -not(Test-Path ($_.FullName -replace ".webp","-thumb.webp"))}
Set-Location -Path $dir
$size = -join($width, "x",$heigth)
foreach($image in $voorbeeld) {
$baseName = $image.BaseName
$extension = $image.Extension
$outputName = $baseName + "-thumb" + $extension
convert $image.name -resize $size $outputName
}
question from:
https://stackoverflow.com/questions/65937377/how-to-let-a-script-run-for-all-subfolders-in-the-chosen-directory-via-powershel 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…