Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

How to let a script run for all subfolders in the chosen directory via Powershell?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using Get-ChildItem you can use the -Recurse parameter to go through all child locations specified.

More information in the PowerShell documentation,

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...