首页 > 解决方案 > Powershell Get-Random AND Rename-Item

问题描述

我正在尝试将文件夹中的所有文件重命名为随机数。目前他们在每个文件名中都有日期,这没有帮助。

这是我的简单脚本:

$path = "C:\temp\photos\"

$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}

任何投入将不胜感激。

标签: powershell

解决方案


根据 Olaf 的评论并稍作调整:
$path = "C:\temp\photos"
$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:\temp\photos\*"
ForEach ($file in $files) {
  Rename-Item -Path $file.FullName -NewName ([String]$(Get-Random) + $file.Extension)
}

没有包含任何代码来防止生成重复的随机名称,这超出了您的问题范围


推荐阅读