首页 > 解决方案 > Rename file with powershell (variable file name structure)

问题描述

Currently I'am facing an issue in renaming file names with powershell. I'am actually able to rename files in a particular folder, however if the structure is different the command fails.

Example files:

test file - 1234 - copy.docx
test file - 1234.pdf

I was running the following command:

Get-ChildItem <location> -file | foreach {
Rename-Item -Path $_.FullName -NewName ($_.Name.Split("-")[0] + $_.Extension) }

I want to keep the filename before the last "-". But if I run my command, I always get file name before the first "-".

Any advice for a better approach?

标签: powershellfilerename

解决方案


Most straightforward approach:

Get-ChildItem <location> -File | Rename-Item -NewName {
    $index = $_.BaseName.LastIndexOf("-")
    if ($index -ge 0) {
        $_.BaseName.Substring(0, $index).Trim() + $_.Extension
    }
    else { $_.Name }
}

Regex replace:

Get-ChildItem <location> -File |
  Rename-Item -NewName {($_.BaseName -replace '(.*)-.*', '$1').Trim() + $_.Extension}

推荐阅读