Pad IP addresses with leading 0's - powershell

孤街醉人 提交于 2021-02-19 07:52:23

问题


I'm looking to pad IP addresses with 0's

example
1.2.3.4 -> 001.002.003.004
50.51.52.53 -> 050.051.052.053

Tried this:

[string]$paddedIP = $IPvariable
[string]$paddedIP.PadLeft(3, '0')

Also tried split as well, but I'm new to powershell...


回答1:


You can use a combination of .Split() and -join.

('1.2.3.4'.Split('.') | 
    ForEach-Object {$_.PadLeft(3,'0')}) -join '.'

With this approach, you are working with strings the entire time. Split('.') creates an array element at every . character. .PadLeft(3,'0') ensures 3 characters with leading zeroes if necessary. -join '.' combines the array into a single string with each element separated by a ..


You can take a similar approach with the format operator -f.

"{0:d3}.{1:d3}.{2:d3}.{3:d3}" -f ('1.2.3.4'.Split('.') |
    Foreach-Object { [int]$_ } )

The :dN format string enables N (number of digits) padding with leading zeroes.

This approach creates a string array like in the first solution. Then each element is pipelined and converted to an [int]. Lastly, the formatting is applied to each element.




回答2:


To complement AdminOfThings' helpful answer with a more concise alternative using the -replace operator with a script block ({ ... }), which requires PowerShell Core (v6.1+):

PSCore> '1.2.3.50' -replace '\d+', { '{0:D3}' -f [int] $_.Value }

001.002.003.050

The script block is called for every match of regex \d+ (one or more digits), and $_ inside the script block refers to a System.Text.RegularExpressions.Match instance that represents the match at hand; its .Value property contains the matched text (string).



来源:https://stackoverflow.com/questions/58085835/pad-ip-addresses-with-leading-0s-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!