将变量格式化为带前导零的 4 位数字

Format variable as 4 digits with leading zeroes

店号可以是1-4位数字。

就设备的命名方式而言,商店 #26 将是 0026,但我想让技术人员能够轻松地键入 26 以获得相同的结果。

如何获取此变量并通过附加前导零将其格式化为始终为 4 位数字?

## Ask user for store number and affected AP number to query
$Global:Store = Read-Host "Store Number ";
$Global:apNumber= Read-Host "AP Number ";

## Clean up input for validity
IF($store.length -le 4) {
  $store = 
}

您将使用 -format 运算符:

'{0:d4}' -f $variable

https://ss64.com/ps/syntax-f-operator.html

如果你的变量是整数,上面的方法将起作用,如果不是,你可以将它转换为整数:

'{0:d4}' -f [int]$variable

只是为了避免浪费 PetSerAl 的有用帮助(应该在某个时候删除评论):

除了使用 (-f) 之外,我认为这是首选方法,您还可以使用相应值提供的格式化方法。

  • 如果值是一个字符串(就像你的情况一样),你可以用零填充它:

    '26'.PadLeft(4, '0')
    
  • 如果值为数字,您可以将其格式化为字符串:

    (26).ToString('0000')
    

在此处添加其他人的答案,如果您想 make/change 数据数组具有特定的前导零结构(或对数据的任何其他更改),您可以这样做:

$old_array = (0..100)
$new_array = @()
$old_array | % { $new_array += "{0:d3}" -f $_}

foreach 版本的 padleft 和 tostring。第一个的0要加引号:

'4' | % padleft 4 '0'
0004

4 | % tostring 0000
0004

使用范围:

1..10 | % tostring 0000

0001
0002
0003
0004
0005
0006
0007
0008
0009
0010

带前缀:

1..10 | % tostring COMP0000

COMP0001
COMP0002
COMP0003
COMP0004
COMP0005
COMP0006
COMP0007
COMP0008
COMP0009
COMP0010