我正在尝试将文件夹中的所有文件重命名为随机数。目前,他们在每个文件名中都有日期,这没有帮助。
这是我的简单脚本:
$path = "C:tempphotos"
$files = Get-ChildItem -Path $path
Foreach ($file in $files) {
$random = Get-Random
$file | Rename-Item -NewName {$Random + $_.extension}
}
然而,我得到了以下错误:
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 line:7 char:22
+ Rename-Item -NewName {$Random + $_.extension}
如有任何意见,我们将不胜感激。
根据Olaf的评论并稍作调整:
$path = "C:tempphotos"
$files = Get-ChildItem -Path $path
ForEach ($file in $files) {
$random = Get-Random
Rename-Item -Path $file.FullName -NewName ($random + $file.Extension)
}
然而,你可能会把它缩短一点:
$files = Get-Item -Path "C:tempphotos*"
ForEach ($file in $files) {
Rename-Item -Path $file.FullName -NewName ([String]$(Get-Random) + $file.Extension)
}
没有包含任何代码来防止生成重复的随机名称,这超出了您的问题范围。
如果将随机数设为字符串,则对我有效,假设get childitem返回任何结果。
$files = Get-ChildItem -Path $path
Foreach ($file in $files) {
$random = Get-Random
$file | Rename-Item -NewName {"$Random" + $_.extension} -whatif
}
What if: Performing the operation "Rename File" on target
"Item: C:Usersadminfile1.jpg
Destination: C:Usersadmin1968532966.jpg".
或者作为一个管道:
(get-childitem $path) | rename-item -newname { "$(get-random)" + $_.extension} -whatif