none
SOLVED: Formatting numbers 1 digit too two digit RRS feed

  • Question

  • Tryin to create a function that generate a working mac address.

    When i pass single digit in i get single digits out... it should ad a 0 if it at single digit.

    is the command wrong?     $Number = '{0:D2}' -f [int]$Number # Format number as 2 digits

    Function New-MacAddress
    {
        param
        (
            [Parameter(Mandatory=$true)]
            [ValidateRange(0,99)]
            [Int]
            $Number
        )
            
        $LastPartOfComputerName = $env:COMPUTERNAME.Substring(3,4)
        $Number = '{0:D2}' -f [int]$Number # Format number as 2 digits
    
        $macAddress = "005056$LastPartOfComputerName$Number"
        $macAddress = $macAddress.Insert(2,':').Insert(5,':').Insert(8,':').Insert(11,':').Insert(14,':')
    
        return $macAddress
    }
    
    New-MacAddress -Number '1'
    it return 00:50:56:26:32:1



    #LnQ¯\_(ツ)_/¯


    • Edited by LongQuo Sunday, January 15, 2017 12:57 PM solved
    Saturday, January 14, 2017 10:25 PM

Answers

All replies

  • $i = 9
    $s = '0'+$i
    $s.SubString($s.Length-2,2)


    \_(ツ)_/



    • Edited by jrv Saturday, January 14, 2017 11:30 PM
    Saturday, January 14, 2017 11:27 PM
  • Method #2

    $i = 4
    '{0:D2}' -f $i


    \_(ツ)_/

    • Marked as answer by LongQuo Sunday, January 15, 2017 12:55 PM
    Saturday, January 14, 2017 11:32 PM
  • i renamed the variable and now it working. Thanks for your solutions... like the method #2 less lines

    corrected working code:

    Function New-MacAddress
    {
        param
        (
            [Parameter(Mandatory=$true)]
            [ValidateRange(0,99)]
            [Int]
            $Number
        )
            
        $LastPartOfComputerName = $env:COMPUTERNAME.Substring(3,4)
        $Last_digits = '{0:D2}' -f [int]$Number # Format number as 2 digits
    
        $macAddress = "005056$LastPartOfComputerName$Last_digits"
        $macAddress = $macAddress.Insert(2,':').Insert(5,':').Insert(8,':').Insert(11,':').Insert(14,':')
    
        return $macAddress
    }
    
    New-MacAddress -Number '1'


    #LnQ¯\_(ツ)_/¯

    Sunday, January 15, 2017 12:56 PM
  • Your code won't work as posted.

    \_(ツ)_/

    Sunday, January 15, 2017 1:00 PM