powershell - 外壳 | 用随机名称重命名文件
问题描述
我正在制作一个脚本来用随机名称重命名特定文件。但是在运行的时候,总是出现如下错误:
It is not possible to convert the value ".jpg" to the type "System.Int32". Error: "The input string was not in the correct format."
In C:\Windows\system32\WindowsPowerShell\v1.0\Modules\SetDiscordWallpaper\SetDiscordWallpaper.ps1:7 character:7
+ Rename-Item -Path $file.FullName -NewName ($random + $file.Exte ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastFromStringToInteger
这是我正在使用的代码
function Set-DiscordWallpaper {
$path = "C:\Windows\Temp\*"
foreach($file in $(Get-ChildItem -Path $path -Include "Wallpaper.jpg")) {
$extension = [System.IO.Path]::GetExtension($file.FullName);
$randomName = [System.IO.Path]::ChangeExtension([System.IO.Path]::GetRandomFileName(), $extension)
$newPath = "C:\inetpub\wwwroot\"
Write-Host "Changing File $($file.Name) to $randomName"
Move-Item -Path $file.FullName -Destination $newPath
}
}
我请你帮帮我。我在等待答案。谢谢
解决方案
代码(您问题的第二部分)很好地创建了新的随机文件名,只有该行Move-Item -Path $file.FullName -Destination $newPath
对该新名称不做任何事情,并将具有原始名称的文件移动到新路径。
将该行更改为
Move-Item -Path $file.FullName -Destination (Join-Path -Path $newPath -ChildPath $randomName)
因此文件将在新路径中使用随机名称移动。
或者您是否打算将文件复制到新的目的地,将原始文件名保留在那里,然后重命名原始文件?
在这种情况下,请执行以下操作:
Write-Host "Changing File $($file.Name) to $randomName"
Copy-Item -Path $file.FullName -Destination $newPath # copy with original name
$file | Rename-Item -NewName $randomName # rename the original file
推荐阅读
- javascript - Javascript Calculator - 如何有效地对具有相同类的按钮进行编程而不会出错?
- ruby-on-rails - 从数据库中删除整个条目
- python - 试图找到两个数字之间的数字总和
- php - GET 请求是否应该存储到数据库?
- ios - 获取数组中字典的值
- arrays - 如果所有元素都等于某个值,则从 numpy 数组中删除行/列
- android - 为什么我的 Android 应用程序类占用这么多空间
- google-cloud-platform - 在 GCP 上使用基于存储桶的负载均衡器时如何修复域 DNS 配置?
- mongodb - Mongodb“无法在元素中创建字段'x'”
- javascript - 需要帮助获取价值 Google Maps API .pac-container 类