修改PowerShell脚本实现递归子文件夹移动竖屏图片
解决PowerShell脚本递归处理子文件夹并在对应目录创建portrait文件夹的问题
问题描述
现有一个PowerShell脚本可将竖屏图片移动到当前目录下的portrait子文件夹,但仅能在图片所在目录执行。需要修改脚本,使其能在父文件夹中执行,递归处理所有子文件夹,并在每个子文件夹内创建独立的portrait文件夹存放该文件夹内的竖屏图片,效果如下:
# 执行前 Folder(脚本存放于此) ├─ SubFolder1(图片存放于此) ├─ SubFolder2(图片存放于此) └─ SubFolder3(图片存放于此) # 执行后 Folder ├─ SubFolder1 │ └─ portrait(SubFolder1的竖屏图片移至此) ├─ SubFolder2 │ └─ portrait(SubFolder2的竖屏图片移至此) └─ SubFolder3 └─ portrait(SubFolder3的竖屏图片移至此)
原脚本
Add-Type -AssemblyName System.Drawing $ImageList = Get-ChildItem "*.jp*g" $LandscapePath = "" $PortraitPath = "portrait" md portrait Foreach($ImageFile in $ImageList) { #Get the image information $image = New-Object System.Drawing.Bitmap $ImageFile.Fullname #Get the image attributes $ImageHeight = $image.Height $ImageWidth = $image.Width #Close the image $image.Dispose() If($ImageWidth -lt $ImageHeight) { Move-Item -LiteralPath $ImageFile.FullName -Destination $PortraitPath -Force } }
尝试的错误修改
添加-Recurse参数后,所有子文件夹的图片被统一移到父文件夹的portrait中,不符合需求:
$ImageList = Get-ChildItem "*.jp*g" -Recurse
修改后的脚本
Add-Type -AssemblyName System.Drawing # 递归获取所有子文件夹中的jp(e)g图片文件 $ImageList = Get-ChildItem "*.jp*g" -Recurse -File Foreach($ImageFile in $ImageList) { # 获取当前图片所在的文件夹路径 $currentDir = $ImageFile.DirectoryName # 构造当前文件夹下的portrait路径 $PortraitPath = Join-Path -Path $currentDir -ChildPath "portrait" # 如果portrait文件夹不存在则创建 if (-not (Test-Path -Path $PortraitPath)) { New-Item -ItemType Directory -Path $PortraitPath | Out-Null } # 获取图片尺寸信息 $image = New-Object System.Drawing.Bitmap $ImageFile.Fullname $ImageHeight = $image.Height $ImageWidth = $image.Width $image.Dispose() # 判断为竖屏则移动到当前目录的portrait文件夹 If($ImageWidth -lt $ImageHeight) { Move-Item -LiteralPath $ImageFile.FullName -Destination $PortraitPath -Force } }
关键改动说明
- 移除了提前在父目录创建
portrait的代码,改为针对每个图片所在的文件夹按需创建portrait目录 - 使用
Join-Path构造当前图片目录下的portrait路径,确保每个子文件夹的竖图都移到自身的portrait中 - 添加
-File参数到Get-ChildItem,避免误处理目录(虽然*.jp*g不会匹配目录,但更严谨) - 用
Test-Path检查portrait目录是否存在,避免重复创建报错
内容的提问来源于stack exchange,提问作者Mister Nobody
相关产品推荐
相关产品推荐

