【问题标题】:Replace Part of Filename if Filename Already Exists如果文件名已经存在,则替换文件名的一部分
【发布时间】:2019-08-16 15:25:24
【问题描述】:

在这个问题中,如果新重命名的文件名已经存在,我该如何重命名文件名的一部分?希望新尝试的文件名覆盖现有文件。还想重命名文件夹内文件夹内的文件夹。

将文件名中的“默认”替换为“VOD”,

Replace Part of File Name Powershell

Get-ChildItem Default_*.csv |
    Rename-Item -NewName {$_.Name -replace '^Default','VOD'}

ls *.csv | Rename-Item -NewName {$_.Name -replace "Default","VOD"}

这里的解决方案不适用于-Force

Get-ChildItem *.* -File -Recurse |
    Rename-Item -NewName {$_.Name -replace 'Default','VOD'} -Force

【问题讨论】:

    标签: powershell


    【解决方案1】:

    根据这个问答:rename-item and override if filename exists

    使用Move-Item-Destination,并将$_.Name 替换为$_.FullName(如果你不这样做,它会将所有内容都放入当前目录,因为Name 只是文件名,而不是完整路径)。使用-WhatIf查看会执行哪些操作,以防万一:

    -WhatIf

    Get-ChildItem *.* -File  -Recurse |
        Move-Item -Destination {$_.FullName -replace 'Default','VOD'} -WhatIf
    

    输出:

    如果:对目标“项目:C:\temp\pstest\Default_77.txt 目标:C:\temp\pstest\VOD_77.txt”执行“移动文件”操作。

    现在-Force

    当您对使用 -WhatIf 参数的输出感到满意时,将其更改为 -Force 以完成文件移动。

    Get-ChildItem *.* -File  -Recurse | 
        Move-Item -Destination {$_.FullName -replace 'Default','VOD'} -Force
    

    【讨论】:

      猜你喜欢
      • 2014-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-02
      • 2014-07-20
      • 1970-01-01
      相关资源
      最近更新 更多