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

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.


Solution 1:

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

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

Solution 2:

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_"}

Solution 3:

To remove prefix of all in folder:

Get-ChildItem 'Folderpath\KB*' | Rename-Item -NewName { $_.Name -replace 'KB*','' }

To Add a prefix to all in folder:

foreach($item in 'Folderpath')
{
Get-ChildItem 'C:\Users\ilike\OneDrive\Desktop\All in one script\Single Patch here' | Rename-Item -NewName { "KB" + $_.Name }
}

Took a while, hope this can help others in need