首页 > 解决方案 > 外壳 | 用随机名称重命名文件

问题描述

我正在制作一个脚本来用随机名称重命名特定文件。但是在运行的时候,总是出现如下错误:

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

我请你帮帮我。我在等待答案。谢谢

标签: powershell

解决方案


代码(您问题的第二部分)很好地创建了新的随机文件名,只有该行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

推荐阅读