+1 on String Variable to retain leading 0

Son 301 Reputation points
2021-07-19T13:58:01.83+00:00

Hi,

I have the following code:

$Members = Get-UnifiedGroupLinks -Identity "NameOfGroup" -LinkType Members | select PrimarySmtpAddress
[int]$live_number = 012345678

$UserDetails = @()
foreach ($Member in $Members)
{
$Member
$UserDetails += Get-AzureADUser -SearchString $Member.PrimarySmtpAddress | select @{n="live_number";e={$live_number}},@{n="mobile_number";e={$_.Mobile}},@{n="email_address";e={$_.UserPrincipalName}}
$live_number++
}

I am trying to do a +1 on the $live_number variable in the foreach loop. Basically I need to assign a number to each user returned in the loop which needs to be +1 from the original number defined in the variable. The issue I am facing is that the zero is dropped but I need the 0 as it is part of a phone number. An integer drops the zero but I need it to be an integer to use the $live_number++ command. So I am not sure how to retain the zero without turning the variable into a string but then the $live_number++ will not work.

Hope that makes sense, very new to PS so I am sure there is lots of room for improvement on how I am doing / done things.

Cheers

Son

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,282 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 44,006 Reputation points
    2021-07-19T14:49:16.667+00:00

    Leading zeros in a numeric value are inconsequential You need to convert the integer (in this case) to a string in a way that "pads" the conversion with leading zeros.

    You can use the "ToString" method to accomplish this. Here's an example:

    [int]$live_number = 012345678
    $UserDetails = @()
    $Members = 1..5
    foreach ($Member in $Members) {
        $UserDetails += "" | Select-Object $Member.ToString("d2"), @{n = "live_number"; e = { $live_number.ToString("d9") } }
        $live_number++
    }
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. MotoX80 30,916 Reputation points
    2021-07-19T14:50:14.457+00:00

    Use padleft.

    [int]$intLive_number = 012345678
    
    $numlength  = 9                  # the number of characters we want to display
    
    for ($i=0; $i -lt 10; $i++)
    {
        $intLive_number++   
        $strLive_number = $intLive_number.ToString().PadLeft($numlength,"0")
        $strLive_number              # display our number with leading zeroes      
    }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.