我编写了一个脚本来转换和调整项目图片的大小。它为目录集转换和调整大小,但我也想覆盖子目录中的文件。我怎样才能让这个脚本为所选目录中的所有子目录运行?
$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
}
答案 0 :(得分:1)
使用 Get-ChildItem
,您可以使用 -Recurse
参数遍历指定的所有子位置。
PowerShell 文档中的更多信息,