Increment Alphanumeric

Welcome Forums General PowerShell Q&A Increment Alphanumeric

Viewing 5 reply threads
  • Author
    Posts
    • #177834
      Participant
      Topics: 16
      Replies: 32
      Points: 80
      Rank: Member

      I have a stupid and likely simple question that has perplexed me.

       

      I need to be able to increment an alphanumeric string by 1 for a script.

      I basically need to be able to set a variable to equal "T01" + 1

      Any assistance would be greatly appreciated.

       

    • #177849
      Participant
      Topics: 1
      Replies: 9
      Points: 84
      Helping Hand
      Rank: Member

      Hii,

      This is the first thing which came up in my mind. Works for you?? You can make the changes as per your requirement.

      
      $i = 01
      $i++
      $str = "T$i"
      Write-Host $str
      
      
    • #177861
      Participant
      Topics: 9
      Replies: 427
      Points: 712
      Helping Hand
      Rank: Major Contributor

      I recommend the padleft method of the string class

      1..10 | foreach { "T$(([String]($_)).PadLeft(2,'0'))" }
      
    • #177873
      Participant
      Topics: 16
      Replies: 32
      Points: 80
      Rank: Member

      My difficulty and I should have mentioned this is that the "T01" is being provided to the script as a parm in the script execution command line so it is a var in the script. So I was trying to accomplish this with a little rewriting of the scripts as possible.

    • #177888
      Participant
      Topics: 2
      Replies: 1707
      Points: 3,428
      Helping Hand
      Rank: Community Hero

      So you might have explained a little more detailed what you're trying to do. Ideally with some examples of the data before and after. If I got it right you could use something like this:

      $Result = 'T01' -match '(\w)(\d+)'
      If ($Result){
          "{0}{1:0#}" -f $Matches[1], $([INT]$Matches[2] + 1 )
      }
    • #177897
      Participant
      Topics: 16
      Replies: 32
      Points: 80
      Rank: Member

      Yes I should have added more details 🙂

      Your solution was perfect. Thanks a bunch!

       

Viewing 5 reply threads
  • The topic ‘Increment Alphanumeric’ is closed to new replies.