【问题标题】:Optimizing a powershell batch rename scriptOptimizing a powershell batch rename script
【发布时间】:2022-12-01 22:38:31
【问题描述】:

I wrote the script below to batch rename files with powershell. It is intended to remove dots (.) and every (-) that is followed by a number from the filenames. Example: text.10-1 becomes text101. However, I feel like there must be a way to do this in a line of code. Also, I wanted it to also enter a subdirectory and do it, how do I write it?


Get-ChildItem | ForEach{ $_ | Rename-Item -NewName "$($_.BaseName.Replace("-1",'1')+$_.Extension)" }

Get-ChildItem | ForEach{ $_ | Rename-Item -NewName "$($_.BaseName.Replace("-0",'0')+$_.Extension)" }

Get-ChildItem | ForEach{ $_ | Rename-Item -NewName "$($_.BaseName.Replace("-2",'2')+$_.Extension)" }

Get-ChildItem | ForEach{ $_ | Rename-Item -NewName "$($_.BaseName.Replace("-3",'3')+$_.Extension)" }

Get-ChildItem | ForEach{ $_ | Rename-Item -NewName "$($_.BaseName.Replace("-4",'4')+$_.Extension)" }

Get-ChildItem | ForEach{ $_ | Rename-Item -NewName "$($_.BaseName.Replace("-5",'5')+$_.Extension)" }
Get-ChildItem | ForEach{ $_ | Rename-Item -NewName "$($_.BaseName.Replace("-6",'6')+$_.Extension)" }

Get-ChildItem | ForEach{ $_ | Rename-Item -NewName "$($_.BaseName.Replace("-7",'7')+$_.Extension)" }

Get-ChildItem | ForEach{ $_ | Rename-Item -NewName "$($_.BaseName.Replace("-8",'8')+$_.Extension)" }

Get-ChildItem | ForEach{ $_ | Rename-Item -NewName "$($_.BaseName.Replace("-9",'9')+$_.Extension)" }```

Thanks

【问题讨论】:

    标签: powershell performance


    【解决方案1】:

    You can do this with a single Get-ChildItem call:

    (Get-ChildItem -Path 'D:Test' -File -Recurse) | Where-Object { $_.BaseName -match '[-.]' } |
    Rename-Item -NewName {'{0}{1}' -f ($_.BaseName -replace '[-.]+'), $_.Extension} -WhatIf
    

    Note: I have added switch -WhatIf for safety so you can first see whatwouldhappen in the console. When you are satisfied with that, remove the -WhatIf switch and run again to actually start renaming the files.

    switch -Recurse lets Get-ChildItem also find files in subfolders

    【讨论】:

      【解决方案2】:

      How about this? Get-childitem in parens to avoid the "modifying the loop" problem.

      echo hi | set-content -1.txt,-2.txt,-3.txt
      (get-childitem) | rename-item -newname { $_.name -replace '-(d)','$1' } -whatif
      
      What if: Performing the operation "Rename File" on target "Item: C:usersdminoo-1.txt Destination: C:usersdminoo.txt".
      What if: Performing the operation "Rename File" on target "Item: C:usersdminoo-2.txt Destination: C:usersdminoo.txt".
      What if: Performing the operation "Rename File" on target "Item: C:usersdminoo-3.txt Destination: C:usersdminoo.txt".
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-02
        • 2017-01-12
        • 1970-01-01
        • 2022-12-01
        • 2017-09-10
        • 1970-01-01
        相关资源
        最近更新 更多