2

I'd like to add underscore character "_" at position 22 of a filename. What would be the PowerShell command to do it?

3
  • Rename-Item can rename files for you. Commented 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. Commented 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. Commented Feb 2, 2016 at 8:48

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank You. This is exactly what I was asking for. Have a good day, kind sir.
1

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

This one does not add underscore, it replaces any character at position 22 with the underscore character.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.