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

时间:2021-01-28 12:46:26

标签: 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

}

1 个答案:

答案 0 :(得分:1)

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

PowerShell 文档中的更多信息,

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