question

Son-3712 avatar image
0 Votes"
Son-3712 asked MotoX80 answered

+1 on String Variable to retain leading 0

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
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

RichMatheisen-8856 avatar image
0 Votes"
RichMatheisen-8856 answered

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++
 }
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

MotoX80 avatar image
0 Votes"
MotoX80 answered

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      
 }
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.