Strong typing variable length

Welcome Forums General PowerShell Q&A Strong typing variable length

This topic contains 0 replies, has 1 voice, and was last updated by  Forums Archives 6 years, 10 months ago.

  • Author
  • #5506

    Points: 0
    Rank: Member

    by JasonH at 2013-02-04 09:09:21

    I have a script that takes a six-digit employee number as an argument. The employee numbers may lead with one or more zeros and, by default, powershell removes the leading zeros even if I strong type the variable as string. I need to ensure the variable is always six digits and leading zeros are not removed. The solution I have right now seems overkill and I'm hoping for a more efficient way to do this. This is what I'm doing now using the -f (format) operator:

    $args[0] | foreach {$employeeNumber = "{0:D6}" -f $_}

    Any suggestions? Thanks!

    by DonJ at 2013-02-04 09:14:59

    There's no way to "type" a variable to a given length. You can, however, use a regular expression, or the Length property of a [string], to ensure the variable's contents matches your requirements. When accepting input on a parameter, you can also use a Validation attribute to ensure that only proper data is provided to the parameter. Validation can include length or a regular expression pattern.

    In terms of the leading zeros, what you're doing is correct and is probably the best way to do it. On a String object, there are also Padleft() and PadRight() methods that you could use.

The topic ‘Strong typing variable length’ is closed to new replies.