Nitin Gupta
Nitin Gupta

Reputation: 9

Adding an auto-incrementing number to a file name string

I would like my PowerShell script to modify the name of the file by increment number every time.

This is my file name: abc-0.2.0.1-SNAPSHOT-barista.zip. I want to write a syntax that will increment it every time like mentioned below:

abc-0.2.0.2-SNAPSHOT-barista.zip
abc-0.2.0.3-SNAPSHOT-barista.zip
abc-0.2.0.4-SNAPSHOT-barista.zip
abc-0.2.0.5-SNAPSHOT-barista.zip
abc-0.2.0.6-SNAPSHOT-barista.zip
abc-0.2.0.7-SNAPSHOT-barista.zip
abc-0.2.0.8-SNAPSHOT-barista.zip
abc-0.2.0.9-SNAPSHOT-barista.zip
abc-0.2.0.10-SNAPSHOT-barista.zip
abc-0.2.0.11-SNAPSHOT-barista.zip

and so on …

Upvotes: 0

Views: 1515

Answers (3)

user6811411
user6811411

Reputation:

To evaluate the highest number you need to first get them to an equal length, otherwise with alpha sorting 10 is less than 9.


I was still struggling with the RegEx but Ansgar was faster, so I'll combine these two parts

$Last = Get-ChildItem abc-*-SNAPSHOT-barista.zip | 
  Sort-Object {[Regex]::Replace($($_.Basename),'\d+',{$args[0].Value.PadLeft(10, '0')})}|
    Select -Last 1

[regex]$re = '(.*?\.)(\d+)(-SNAPSHOT-.*\.zip)'
$cb = {
      $a, $b, $c = $args[0].Groups[1..3].Value
      '{0}{1}{2}' -f $a, ([int]$b+1), $c
}
$re.Replace($Last.Name, $cb)

Sample output:

> Q:\Test\2017\08\18\SO_45748408.ps1
abc-0.2.0.12-SNAPSHOT-barista.zip

Upvotes: 1

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

Use a regular expression replacement with a callback function:

$name = 'abc-0.2.0.4-SNAPSHOT-barista.zip'

[regex]$re = '(.*?\.)(\d+)(-SNAPSHOT-.*\.zip)'
$cb = {
    $a, $b, $c = $args[0].Groups[1..3].Value
    '{0}{1}{2}' -f $a, ([int]$b+1), $c
}

$re.Replace($name, $cb)

Upvotes: 3

Steven Zheng
Steven Zheng

Reputation: 13

What you can do is set the 0.2.0.x bit to a variable

$version = 3

Then everytime you perform an action increase that variable by one ie.

*perform action*
$version++

Upvotes: 0

Related Questions