Mike Kent
Mike Kent

Reputation: 13

How to replace first characters in a file name with a string?

I've been working on a script to maintain the archive from my IP camera DVR. My recording software outputs filenames formatted so that the first character is the camera number, followed by a date and time stamp.

ex. 1_2017-11-03_00-45-07.avi

I want to replace the first character with a string that represents the camera.

ex. DivertCam_2017-11-03_00-45-07.avi

So far, I have:

Get-ChildItem  "D:\DivertCam\1_*.avi" |
    Rename-Item -NewName {$_.Name -replace '1_?','DivertCam_'}

Luckily with -WhatIfand running a transcript, I was able to see that my results would be wrong:

What if: Performing the operation "Rename File" on target "Item: D:\DivertCam\1_2017-11-03_00-45-07.avi Destination: D:\DivertCam\DivertCam_20DivertCam_7-DivertCam_DivertCam_-03_00-45-07.avi"

I know it's just picking out every "1_". How can I make it after the the first instance of "1_", or read the filename like a string, split it into 3 arrays separated by "_" and then change the first array?

Upvotes: 1

Views: 3950

Answers (2)

Gareth Lyons
Gareth Lyons

Reputation: 1972

This will replace everything before the first '_' with 'DivertCam' (note use of % (foreach) to operate on each file individually).

Get-ChildItem "D:\DivertCam\1_*.avi" | % {Rename-Item $_.FullName -NewName "DivertCam$($_.Name.Substring($_.Name.IndexOf('_')))" }

Upvotes: 0

TheMadTechnician
TheMadTechnician

Reputation: 36342

The -replace operator performs a RegEx match and replacement, so you can use RegEx syntax to do what you want. For you the solution is to include the 'beginning of string' characater ^ at the beginning of your match text. Since this is RegEx, the ? means the previous character may or may not exist, so what you are currently matching on is any character matching '1' which may or may not be followed by an underscore. A better version would simply be:

$_.name -replace '^1','DivertCam'

To put that in context with the rest of your line, it would be:

Get-ChildItem  "D:\DivertCam\1_*.avi" | Rename-Item -NewName {$_.name -replace '^1','DivertCam'}

Keep in mind this only works for the -replace operator which uses RegEx (short for Regular Expression) matching, and not the .Replace() method that you may see used, which uses simple pattern matching.

Upvotes: 4

Related Questions