如何让脚本通过Powershell在所选目录中的所有子文件夹运行?



我写了一个脚本来转换和调整一个项目的图片大小。它为目录集转换和调整大小,但我还想涵盖子目录中的文件。我怎样才能让这个脚本对所选目录中的所有子目录运行呢?

$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

}

使用Get-ChildItem,您可以使用-Recurse参数遍历指定的所有子位置。

更多信息见PowerShell文档,

https://learn.microsoft.com/en - us/powershell/module/microsoft.powershell.management/get childitem?view=powershell - 7.1

最新更新