PowerShell: How do I append a prefix to all files in a directory?

2

4

Currently I'm using cmdlets like:

dir | rename-item -NewName {$_.name -replace "-","_"}

But now I need to add a prefix to the filename for all files in the directory.
I can't predict how long each filename is (it varies), so I can't just use a bunch of . wildcards.

I need it to append a fixed phrase to the beginning of each filename, regardless what that filename is.

Giffyguy

Posted 2017-05-07T22:48:08.117

Reputation: 782

1

See solution here http://stackoverflow.com/a/20874916/5518385

– Yisroel Tech – 2017-05-07T22:53:02.657

1What is it now? A prefix or a suffix? For a prefix you already got a name so (literally) just add to your prefix or (for a suffix) just add the suffix to it. – Seth – 2017-05-08T12:09:23.703

Answers

8

An alternative approach to a regular expression would be to use simple string operations to create the new file name.

Get-ChildItem | Rename-Item -NewName { "Prefix_" + $_.Name }

Seth

Posted 2017-05-07T22:48:08.117

Reputation: 7 657

1I'm trying this, but it seems to go mad and keep trying to prefix filenames over and over until it crashes from the filename being too long - e.g. running the command above results in filenames like Prefix_Prefix_Prefix_Prefix_Prefix_Prefix_Prefix_Prefix_Prefix_Prefix_... – Tom Carpenter – 2017-09-02T14:37:43.850

Split the command. $items = Get-ChildItem; And replace the Get-ChildItem in the above case with $items. – Seth – 2017-09-06T10:21:47.967

2

In the end based on this, I just added -Exclude Prefix_* to the Get-ChildItem command.

– Tom Carpenter – 2017-09-06T10:23:53.147

4

You are quite near.

  • -replace uses RegEX and in a Regular Expression you anchor at the beginning with a ^
  • for a suffix you can similarly replace the anchor at line end with $
  • to avoid any possible re-iteration of the renamed file enclose the first element of the pipeline in parentheses.

(Get-ChildItem -File) | Rename-Item -NewName {$_.Name -replace "^","Prefix_"}

LotPings

Posted 2017-05-07T22:48:08.117

Reputation: 6 150

1I like this answer because it doesn't cause an infinite loop and I don't need to write the prefix twice - like what happens in other solutions with the -Exclude Prefix_* to avoid the loop. – TCB13 – 2018-07-16T07:34:48.843