Search code examples
powershellcmd

Rename files in a specific way. Target nth string between symbols


Apologies in advance for a bit vague question (no coding progress).

I have files (they can be .csv but dont have .csv, but that I can add via script easy). The files' name is something like this:

TRD_123456789_ABC123456789_YYMMDD_HHMMSS_12345678_12345_blabla_blabla_blabla_blabla

Now I would need a script that renames the file in a way that it keeps original name except:

  1. It would cut off the ending (blabla_blabla_blabla_blabla) part.
  2. Changes the 12345 before blabla to random 5 characters (can be numbers too)
  3. Change timestamp of HHMMSS to current Hours, minutes, seconds.

In regards to point 3. I think that I can insert arbitary powershell script to any string in " " queotes. So when renaming the files, I was thinking I could just add

Rename-Item -NewName {... + $(get-date -f hhmmss) + ...}

However, I am lost how to write renaming script that renames parts between 4th & 5th _ symbol. And removes string part after 7th _ symbol.

Can somebody help me with the script or help me how to in powershell script target string between Nth Symbols?

Kind Regards, Kamil.


Solution

  • Split the string on _:

    $string = 'TRD_123456789_ABC123456789_YYMMDD_HHMMSS_12345678_12345_blabla_blabla_blabla_blabla'
    
    $parts = $string -split '_'
    

    Then discard all but the first 6 substrings (eg. drop the 12345 part and anything thereafter):

    $parts = $parts[0..5]
    

    Now add your random 5-digit number:

    $parts = @($parts; '{0:D5}' -f $(Get-Random -Maximum 100000))
    

    Update the string at index 4 (the HHMMSS string):

    $parts[4] = Get-Date -Format 'HHmmss'
    

    And finally join all the substrings together with _ again:

    $newString = $parts -join '_'
    

    Putting it all together, you could write a nice little helper function:

    function Get-NewName {
      param(
        [string]$Name
      )
    
      # split and discard
      $parts = $Name -split '_' |Select -First 6
    
      # add random number
      $parts = @($parts; '{0:D5}' -f $(Get-Random -Maximum 100000))
    
      # update timestamp
      $parts[4] = Get-Date -Format 'HHmmss'
    
      # return new string
      return $parts -join '_'
    }
    

    And then do:

    Get-ChildItem -File -Filter TRD_* |Rename-Item -NewName { Get-NewName $_.Name }