silverbackbg
silverbackbg

Reputation: 182

What is the fastest/easiest way to increase a number in a string variable in Powershell?

I have the following Powershell variable

$var = "AB-0045"

I would like to increase the number in the string to become "AB-0046". I can do:

$newNumber = [int]$var.Substring($var.length -4,4) + 1

Which will give me the desired number 46, but then I have to append that 46 as a string to a new string "AB-00". Is there a better way to do that?

Upvotes: 0

Views: 134

Answers (2)

AdminOfThings
AdminOfThings

Reputation: 25021

I tested with regex class Replace() method and string class Split() method with string formatter. Split() seems faster provided your string is always in the same format. The Replace() method does not care what happens before the last 4 numbers:

# Replace Method
[regex]::Replace($var,'\d{4}$',{([int]$args[0].Value+1).ToString('0000')})

# Split method
$a,[int]$b = $var.split('-'); "{0}-{1:0000}" -f $a,++$b

Upvotes: 1

OwlsSleeping
OwlsSleeping

Reputation: 1570

Now that you have the integer, you'll have to convert back to string formatted in the way you'd like and concatenate.

I'd recommend adding to "AB-" rather than "AB-00" in case your number goes over 100.

To pad leading zeros, you can use the -f operator.

e.g. "{0:d4}" -f 45

You'll still need to get the integer first (45 in the example) from your original string.

Upvotes: 2

Related Questions