Author Posts

January 1, 2012 at 12:00 am

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.