Increment Alphanumeric

Welcome Forums General PowerShell Q&A Increment Alphanumeric

This topic contains 5 replies, has 4 voices, and was last updated by

 
Participant
1 month ago.

  • Author
    Posts
  • #177834

    Participant
    Topics: 16
    Replies: 32
    Points: 79
    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: 0
    Replies: 4
    Points: 52
    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: 425
    Points: 691
    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: 79
    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: 1
    Replies: 1552
    Points: 2,700
    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: 79
    Rank: Member

    Yes I should have added more details 🙂

    Your solution was perfect. Thanks a bunch!

     

You must be logged in to reply to this topic.