powershell - 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}
任何投入将不胜感激。
解决方案
根据 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)
}
没有包含任何代码来防止生成重复的随机名称,这超出了您的问题范围。
推荐阅读
- pandas - 当尝试创建一个 DataFrame 时,尽管调用了一个系列,而不是一个字典,但得到 'TypeError: 'dict' object is not callable'?
- django - 使用 Django 服务器服务 React
- python - 如果 else 最后失败并抛出关键错误 - python
- android-studio - 适用于 Android Studio 的 Dart 插件无法处理 .dart 文件
- php - 如何使用 Jquery ajax 和 php 提交表单数据
- html - 图像未在手风琴中显示
- excel - 通过 Windows 调度程序调度启用宏的 Excel 工作表
- spring-boot - JPA Hibernate - 如何(REST api)使用外键作为ID发布对象?
- jquery - jQuery触发嵌套表单rails cocoon上的所有实例
- python - Django ModelForm 未提交