I'd like to add underscore character "_" at position 22 of a filename. What would be the PowerShell command to do it?
-
Rename-Item can rename files for you.DanL– DanL2016-02-02 08:39:27 +00:00Commented Feb 2, 2016 at 8:39
-
Please read the question - I don't want to rename "a" to "b". I want to add underscore at specific position.Rayearth– Rayearth2016-02-02 08:43:28 +00:00Commented Feb 2, 2016 at 8:43
-
I've read the question. It's not clear what you are having difficulty with. If I wanted to rename a file as requested then I would 1) Get the filename into variable called $before 2) Create another variable with the filename modified as intended in a variable called $after. 3) Call Rename-Item $before $after. If you are following a similar process to me then you haven't told us what you are having trouble with 1, 2 or 3? As you ask about renaming and not about creating a string with an underscore in it at a particular position I am assuming it is 3 that you have trouble with.DanL– DanL2016-02-02 08:48:05 +00:00Commented Feb 2, 2016 at 8:48
3 Answers
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
1 Comment
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...
1 Comment
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}}