0

I have folders that were named incrementally, for example Folder 01 TAG Folder 02 TAG Folder 03 TAG and so on. However in the same path, there will be folders that have different name too if that's relevant. Any idea to make powershell return a simple largest increment folder name? Thanks in advance.

Gregor Isack
  • 1,111
  • 12
  • 25

3 Answers3

3

You can use something like the following as starting point...

$numbers = $null
$numbers += (dir "Folder * TAG" | select Name).Name | % { 
   if ($_ -match "(.*)(\d)(.*)") { 
      $Matches[2] 
   } 
}
$maxNumber = [int]($numbers | sort-object -Descending)[0]
$maxNumber++
$foldername = "Folder $maxNumber TAG"
$foldername
Peter Schneider
  • 2,879
  • 1
  • 14
  • 17
  • To also have 2 digits for the (not asked for) **next** free foldername use `$foldername = "Folder {0:00} TAG" -f $maxNumber` (+1) –  Nov 01 '18 at 09:05
  • This works great, however it matches only one digit number (it stopped working for number greater than `09`), I changed the regex to `(.*)(\d{2,2})(.*)` instead. And would you mind explain why `$maxNumber++` is necessary? – Gregor Isack Nov 01 '18 at 09:39
  • $maxNumber++ raises the number by one, as I meant you want to have the next free foldername. So in the case you actually want the last used foldername you can omit the $maxNumber++. – Peter Schneider Nov 01 '18 at 09:59
  • Ahh I see. Thanks for the explanation :) – Gregor Isack Nov 01 '18 at 11:50
3

Since the numbers have a fixed width, sorting on NTFS file systems isn't neccessary.

In case of unsorted file systems and numbers with different places,
I'd use $ToNatural from Ronan Kuzmin it extends every number to 20 places.

$ToNatural = { [regex]::Replace($_, '\d+', { $args[0].Value.PadLeft(20) }) }

Get-ChildItem "Folder [0-9]* TAG" -Dir|Sort-Object $ToNatural|Select-Object -Expand Name -Last 1
2

here's yet another way to do it ... [grin]

# fake reading in a list of directories
#    in real life, use Get-Content -Directory
$DirList = @(
[System.IO.DirectoryInfo]'Folder 02 TAG'
[System.IO.DirectoryInfo]'Folder 03 TAG'
[System.IO.DirectoryInfo]'Dir Some Word'
[System.IO.DirectoryInfo]'Dir Other Word'
[System.IO.DirectoryInfo]'Folder 66 TAG'
[System.IO.DirectoryInfo]'Folder 05 TAG'
[System.IO.DirectoryInfo]'Folder 01 TAG'
)

$NextNumber = [int](($DirList |
    Where-Object {$_ -match ' \d{2} '} |
    Sort-Object |
    Select-Object -Last 1).Name -replace '[^0-9]') + 1

$NextDirName = 'Folder {0:D2} TAG' -f $NextNumber

$NextNumber
$NextDirName

output ...

67
Folder 67 TAG

what it does ...

  • filters out any dir name that has no digits in it
  • sorts the items [defaults to full name]
  • selects the last one
  • grabs the .Name of that object
  • replaces any non digit with nothing
  • coerces the [string] to an [int]
  • adds one to it
  • uses the -f string format operator to make a new Dir name with the new highest number
Lee_Dailey
  • 7,292
  • 2
  • 22
  • 26