Reputation: 234
I'd like to add underscore character "_" at position 22 of a filename. What would be the PowerShell command to do it?
Upvotes: 2
Views: 12737
Reputation: 56
below script will add '-' at position 3 and 6 and 9 and 12 and 15
from: s270120070336.bmp
to: s27-01-20-07-03-36.bmp
Get-ChildItem -Path 'C:\users\sonook\desktop\screenshot' -Filter '*.bmp' |
ForEach-Object { $_ | Rename-Item -NewName {$_.BaseName.insert(3,'-').insert(6,'-').insert(9,'-').insert(12,'-').insert(15,'-') + $_.Extension}}
Upvotes: 0
Reputation: 58931
You could use -replace
and a simple regex to achieve that.
In the following example, I first retrieve the file using the Get-Item cmdlet and rename it using Rename-Item:
Get-Item $YOURPATH | % { $_ | Rename-Item -NewName ($_.Name -replace '^([\S\s]{22})', '$1_')}
You may have to add a check whether the file name is long enough, otherwise it could happen, that you rename the file extension or nothing...
Upvotes: 1
Reputation: 2904
alternately you can also make use of the string method insert
Get-Item -Path $Path |
Rename-Item -NewName {$_.BaseName.insert(22,'_') + $_.Extension} -WhatIf
note: remove -whatif
to apply the rename
Upvotes: 5