简体   繁体   中英

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?

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}

You could use RegEx to achieve the desired output:

Rename-Item -Path $_.FullName -NewName (($_.Name -replace '(.*)-.*?$','$1') + $_.Extension) }

(.*)-.*?$ selects all chars (greedy) until the last - before the end of the line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM