我是 Powershell 新手,对于任何错误的术语,我深表歉意。我看过 SE,我知道如何递归地进入目录结构,但是我能找到的所有工作示例似乎都通过管道传输 Get-ChildItem
的输出,我做不到了解如何在循环迭代之前进一步处理文件。
我想做什么
- 为我的脚本提供一个目录:
C:\Users\Donglecow\myPictures\
。 - 递归循环定义目录中的所有目录(我有一个扩展的文件结构)。
- 查找与过滤器
thumbnail*.jpg
匹配的所有文件,例如:thumbnail_001.jpg
- 将文件重命名为
BACKUP-thumbnail*.jpg
- 检查该图像的尺寸(以像素为单位)并将它们打印到命令行
到目前为止我得到了什么
param (
[string]$dir = $pwd
)
write-output "Working from $($dir)"
$foundJpg = get-childitem -Recurse -Filter thumbnail*.jpg $dir
foreach($file in $foundJpg) {
write-output "Found $($file)"
#Rename to Backup...
#Check image dimensions...
#Do other stuff...
}
这有效并输出正确的文件名,但是当我尝试重命名文件时出现错误。
Rename-Item -NewName { $_.Name.replace("thumbnail", "SAFE-thumbnail.jpg") }
Rename-Item : Cannot evaluate parameter 'NewName' because its argument is specified as a script block and there is no
input. A script block cannot be evaluated without input.
At C:\Users\Donglecow\myPictures\med.ps1:9 char:23
+ ... -Item -NewName { $_.Name.replace("thumbnail", "SAFE-thumbnail.jpg") }
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : MetadataError: (:) [Rename-Item], ParameterBindingException
+ FullyQualifiedErrorId : ScriptBlockArgumentNoInput,Microsoft.PowerShell.Commands.RenameItemCommand
我推断这可能是因为我试图从一个管道输出的命令中进行调整,如 this 上的答案所示。问题:
Get-ChildItem -Recurse -Filter *.mp3 |重命名项目 –NewName { $_.name –replace 'xyz','abc' }
而我为我的循环使用了不同的构造,以便我可以进一步与我找到的每个文件进行交互。
我的环境
作为引用,下面是我的文件结构的一个片段。
C:\Users\Donglecow\myPictures\
1\001\thumbnail_001.jpg
1\002\thumbnail_001.jpg
1\003\thumbnail_001.jpg
2\001\thumbnail_001.jpg
etc...
我哪里错了?
最佳答案
试试这个:
foreach($file in $foundJpg) {
$File | Rename-Item -NewName { $_.Name.replace("thumbnail", "SAFE-thumbnail.jpg") }
#Do other stuff...
}
您需要使用 $file
作为命令的输入(您应该能够通过上面显示的管道执行此操作),因为这是您的 ForEach
循环用于将 Get-ChildItem
检索到的每个项目表示到 $foundJpg
变量中。
关于powershell - 如何递归目录循环、匹配文件名和操作文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46114172/