powershell - 当我想重命名powerShell中for循环中生成的文件时出错

标签 powershell rename-item-cmdlet

这是我的循环

function Generate_bin($input_1, $bin_file_name, $Codes){

   $counter=1 
   foreach ($Code in $Codes)
   {
      Write-Host "Code = $Code" 
      $input_11 = "$input_1" + "$counter"
      $pattern = "0x"
      $New = ""
      $Code = [regex]::replace($Code, $pattern, "$New")
      $bin_file_name2 = "$bin_file_name"
      $bin_file_name2 += "$Code" + ".bin"
      #This utility generates "out.bin"
       Invoke-Command -ScriptBlock {.\xyz.exe -i -t "$input_1"}

      Rename-Item out.bin -NewName $bin_file_name2
      $counter++
   }

}

我收到以下错误
Rename-Item : Cannot create a file when that file already exists.
At C:\script\myParser_unique.ps1:18 char:7
+       Rename-Item out.bin -NewName $bin_file_name2
+       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (C:\Users\v-ashi...Unified\out.bin:String) [Rename-Item], IOException
    + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand

最佳答案

您应该将-Force参数添加到Rename-Item以使其覆盖现有文件。

如果您的代码碰巧生成了多个相等的文件名,则可以在文件名中添加一个计数器。

关于powershell - 当我想重命名powerShell中for循环中生成的文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36923243/

相关文章:

regex - 如何将文件名的一部分移动到不同位置

powershell - 将文件中的所有文本(通配符)替换为起点 Publisher ="{GUID} and ending with a "

powershell - 无法从 Python 项目中递归删除 pyc 文件

powershell - 如何使用 Powershell 查找具有给定名称的所有空目录?

相当于 "tail"命令的 Powershell 几乎可以远程工作

windows - Windows Powershell 中的批量文件和文件夹重命名

powershell - 使用Powershell复制并重命名在前一天修改的文件

powershell - 避免这种 $null 测试的方法

powershell - 重命名项目 : add unique numeric sequence to prevent duplicate file names

powershell - 重命名项目 : Cannot rename because item at . .. 不存在