1

i have a need to replace different string in file names. Is there a way to modify a file name using a find replace function in Powershell?

I have done this in a .bat file but would for this to be done in PS instead.

2
  • i know that will get the all the text in a file, but i just want to do the find replace on the file name itself. Commented Aug 20, 2014 at 18:14
  • possible duplicate of Find characters and rename file name using Powershell Commented Aug 20, 2014 at 18:53

1 Answer 1

3

You didn't provide any details so here's a generic example:

$pattern = "foo"

# Getting all files that match $pattern in a folder.
# Add '-Recurse' switch to include files in subfolders.
$search_results = Get-ChildItem -Path "C:\folder" `
    | Where-Object { ((! $_.PSIsContainer) -and ($_.Name -match $pattern)) } 

foreach ($file in $search_results) {
    $new_name = $file.Name -replace $pattern, "bar"

    # Remove '-WhatIf' switch to commit changes.
    Rename-Item -WhatIf -Path $file.FullName -NewName $new_name
}

Note that $pattern will be treated as a regular expression so escape special characters if you need to catch them.

Sign up to request clarification or add additional context in comments.

2 Comments

exactly was i was looking for, sorry for the vagueness of the question. Thanks you
You can simplify this by piping directly to rename-item and using a scriptblock e.g. ... | Where {...} | Rename-Item -NewName {$_.Name -replace $pattern,'bar'} -whatif.

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.