Saturday, 1 September 2018

PowerShell: Put Number in a Filename in Front of the Filename

I had to work with some files where the interesting number in the filename is not at the start, but after a keyword. So, if I wanted to sort the files in the folder by the interesting number, I’d need to rename the files to put the number at the start. Might seem like a pointless endeavour but I have my reasons.

In the image below is a quick and simple example of how the tool works. I’m interested in the number after CJ, so the keyword to split on is CJ (not a word but you get it), and there are 2 digits we’re interested in. After renaming, I can sort the files in the folder using the special number.

Image: Example of FileNameSorter.ps1

The Script

I named it FileNameSorter.ps1 but you can call it anything you like. Then I ran as .\FileNameSorter.ps1.

Function Wr{
  elseif(!$Args[1]){Write-Host $Args[0] -NoNewLine}
  else{Write-Host $Args[0] -NoNewLine -ForegroundColor $Args[1]}

Wr "Put Number in a Filename in front of the Filename" CYAN;Wr
[System.Object]$Pwd = Pwd
[String]$Current = $Pwd.path

Wr "Current Folder: " CYAN; Wr $Current WHITE;Wr
Wr "Target Folder (or press ENTER to use current): " YELLOW
[String]$Target = Read-Host
If(!$Target){$Target = $Current}
elseif(!(Test-Path $Target)){Wr "$Target is not a valid path!" RED;EXIT}
[System.Array]$Files = (Get-ChildItem -Path $Target).Name

Wr "Files in target:" CYAN;Wr
$Files | Foreach{ Wr $_ WHITE;Wr }

Wr "Keyword to Split on: " YELLOW
[String]$KeyWord = Read-Host

Wr "How many digits in the number: " YELLOW
[Int16]$Digits = Read-Host

Function FNS-Rename-Files{
  $Files | Foreach{
    [System.Array]$S = ($_ -Split $KeyWord)
    If($S.count -gt 1){
      $NosAfterKeyword = ($S[1] -replace '\D+(\d+)','$1')
      If($NosAfterKeyword.length -ge $Digits){
        $Nos = $NosAfterKeyword.Substring(0,$Digits)
        If(!$_.StartsWith($Nos) -and [Bool]($Nos -as [double])){
          If($Rename){Rename-Item ($Target + "\" + $_) ($Nos + "_" + $_)}
          $_ = ($Nos + "_" + $_) 
    Wr $_ WHITE;Wr

Wr "Will rename files to:" CYAN;Wr

Wr "Okay to proceed (Y/N)? " YELLOW
[String]$YesOrNo = Read-Host
If($YesOrNo -ne "Y"){EXIT}

Wr "Files renamed to:" CYAN;Wr
FNS-Rename-Files -Rename

No comments:

Post a Comment
