【问题标题】:Rename file by replacing character and overwrite通过替换字符重命名文件并覆盖
【发布时间】:2014-01-18 14:37:43
【问题描述】:

在 Windows XP 上,在一个文件文件夹中,我需要重命名一些文件,将文件名中的一个字符替换为另一个字符并覆盖任何已经具有该名称的文件。

例如,文件夹包含这两个文件:

fileA.xml
fileb.xml

我需要将fileA.xml重命名为fileb.xml,覆盖原来的fileb.xml

使用 PowerShell,我有这个命令:

Get-ChildItem *.* -include *.xml | Rename-Item -NewName { $_.name.Replace("A","b")}

重命名不起作用,因为文件已经存在。

不必在 PowerShell 中完成,但这是我迄今为止最接近的。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    您可以尝试使用Move-Item 命令,使用-Force 参数。

    Get-ChildItem . -include *.xml | Move-Item -Destination { $_.name.Replace("A","b")} -Force
    

    【讨论】:

      【解决方案2】:

      首先,您需要过滤以获取您实际要重命名的文件。

      Get-ChildItem . -include *.xml | Where-Object { $_.name -match "A$" }
      

      并将其提供给 Move-Item 以重命名:

      Get-ChildItem . -include *.xml | Where-Object { $_.name -match "A$" } | Move-Item -destination { $_.name -replace "A$", "b" }
      

      【讨论】:

      • 你的意思是Where-Object,而不是Where-Item
      • @iCodez - 是的,当你只使用 ?{} 时会发生这种情况:)
      • 感谢您的建议。但我无法让它工作。
      猜你喜欢
      • 1970-01-01
      • 2019-03-24
      • 2021-02-12
      • 1970-01-01
      • 2018-12-31
      • 2012-06-16
      • 2019-02-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多