2

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?

2 Answers 2

3

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}
Sign up to request clarification or add additional context in comments.

Comments

-1

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.

1 Comment

You should try to remove the trailing whitespace after the replace. Also use BaseName, else you end up with a double extension if there is no hyphen.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.