使用前导0填充IP地址-Powershell [英] Pad IP addresses with leading 0's - powershell

查看:145
本文介绍了使用前导0填充IP地址-Powershell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用0填充IP地址

示例
1.2.3.4-> 001.002.003.004
50.51.52.53-> 050.051.052.053

example
1.2.3.4 -> 001.002.003.004
50.51.52.53 -> 050.051.052.053

尝试过:

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

也尝试过拆分,但是我是Powershell的新手...

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

推荐答案

您可以使用.Split()-join的组合.

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

使用这种方法,您一直都在使用字符串. Split('.')在每个.字符处创建一个数组元素. .PadLeft(3,'0')如有必要,确保3个字符的前导零. -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 ..

您可以使用格式运算符-f采取类似的方法.

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]$_ } )

:dN格式的字符串启用N(数字位数)以前导零填充.

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

这种方法会像第一个解决方案一样创建一个字符串数组.然后,将每个元素进行流水线处理并转换为[int].最后,将格式应用于每个元素.

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.

这篇关于使用前导0填充IP地址-Powershell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆