How does one rename the following files (New => Old):
filename__Accelerated_C____Practical_Programming_by_Example.chm -> C Practical Programming by Example.chm
filename__Python_Essential_Reference__2nd_Edition_.pdf -> Python Essential Reference 2nd Edition.pdf
filename__Text_Processing_in_Python.chm -> Text Processing in Python.chm
Open File Explorer, go to a file folder, select View > Details, select all files, select Home > Rename, enter a file name, and press Enter. In Windows PowerShell, go to a file folder, enter dir | rename-item -NewName {$_.name -replace “My”,”Our”} and press Enter.
Powershell: The many ways to use regex The regex language is a powerful shorthand for describing patterns. Powershell makes use of regular expressions in several ways. Sometimes it is easy to forget that these commands are using regex becuase it is so tightly integrated.
To rename and move an item, use Move-Item . You can't use wildcard characters in the value of the NewName parameter. To specify a name for multiple files, use the Replace operator in a regular expression.
Cmdlet. Rename-Item cmdlet is used to rename a folder by passing the path of the folder to be renamed and target name.
Try this one:
Get-ChildItem directory ` | Rename-Item -NewName { $_.Name -replace '^filename_+','' -replace '_+',' ' }
Note that I just pipe the objects to Rename-Item
, it is not really needed to do it via Foreach-Object
(alias is %
).
Update
I haven't anything documented about the 'magic' with scriptblocks. If I remember correctly, it can be used if the property is ValueFromPipelineByPropertyName=$true
:
function x{ param( [Parameter(ValueFromPipeline=$true)]$o, [Parameter(ValueFromPipelineByPropertyName=$true)][string]$prefix) process { write-host $prefix $o } } gci d:\ | select -fir 10 | x -prefix { $_.LastWriteTime }
This should work:
ls | %{ ren $_ $(($_.name -replace '^filename_+','') -replace '_+',' ') }
Expanding the aliases and naming all argument, for a more verbose but arguably more understandable version, the following is equivalent
Get-ChildItem -Path . | ForEach-Object { Rename-Item -Path $_ -NewName $(($_.Name -replace '^filename_+','') -replace '_+',' ') }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With