Vaccano Vaccano - 3 months ago 9
PowerShell Question

Rename parts of file names that match a pattern

Say I have a list of file names like this:

some-file.ts
my-project-service.ts
other.ts
something-my-project.ts


I need to change the file names that have
my-project
in them to have just that part renamed to
$appname$
.

So
my-project-service.ts
would become
$appname$-service.ts


And I need to do this recursively from a root directory.

I seem to be to be hopeless at PowerShell so I thought I would ask here to see if anyone can help me out.

Answer

Use the Get-ChildItem cmdlet with the -recurse switch to get all items recursivly from a root directory. Filter all items containing my-project using the Where-Object cmdlet and finally rename them using the Rename-Item cmdlet:

Get-ChildItem "D:\tmp" -Recurse | 
    Where {$_.Name -Match 'my-project'} | 
    Rename-Item -NewName {$_.name -replace 'my-project','$appname$' } 
Comments