我正在编写一个函数,用于在 PowerShell 中将 IP 地址列表从点分十进制形式转换为无符号整数。这是我的功能:
function Convert-IPtoInteger() {
param(
[Parameter(Mandatory=$true, Position=0, ParameterSetName="IP Address",
ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[string] $addresses
)
process {
foreach ($ip in $addresses) {
if ($ip -match '(\d\d?\d?\.){3}\d\d?\d?') { # approximate regex, matches some impossible addresses like 999.0.0.0
$s = "$ip".Split(".");
[uint32] $x = 0;
(0..3) | ForEach-Object { # positions 0, 1, 2, 3 in previous string
$x = $x -shl 8; # bit shift previous value to the left by 8 bits
$x += $s[$_];
}
Write-Output $x;
}
}
}
}
我曾尝试将其$addresses
声明为如图所示的标量和[string[]]
数组。在这两种情况下,管道多行(使用 shift-enter 创建)会在第一个元素之后导致错误。如果我使用该Get-Content
命令从文件中读取相同的文本,程序将按预期完成。
PS C:\...\1> $example = "192.168.1.1
192.168.2.1"
PS C:\...\1> $example | Convert-IPtoInteger
Cannot convert value "1
192" to type "System.UInt32". Error: "Input string was not in a correct format."
At C:\...\.ps1:16 char:18
+ $x += $s[$_];
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastFromStringToInteger
3232235776
PS C:\...\1> $example > example.txt
PS C:\...\1> Get-Content .\example.txt | Convert-IPtoInteger
3232235777
3232236033
我相信不同之处在于 PowerShell 如何处理换行符。第 16 行 ( $x += $s[$_]
) 似乎以相同的方式读取“1`n192”,而不是将每个元素作为独立$ip
于foreach
语句的元素接收。
该Get-Member
命令显示这$example | Get-Member
是System.String
just like 的一个实例Get-Content .\example.txt | Get-Member
。
我希望我的程序能够正确接受来自文本文件和字符串的输入。我在这里缺少什么?为什么Get-Content
解析与多行字符串不同?
将 IP 地址放在一个对象数组中:
$example = @("192.168.1.1", "192.168.2.1")
$example | convert-IPtointeger
结果:
3232235777
3232236033
之所以不同,是因为您对字符串使用 Foreach-Object:
$example1 = @("192.168.1.1", "192.168.2.1")
$example1.GetType()
$example2 = "192.168.1.1
192.168.2.1"
$example2.GetType()
$example3 = (Get-Content "C:\Users\owain.esau\Desktop\links.txt" )
$example3.GetType()
这将返回以下内容
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
True True String System.Object
True True Object[] System.Array
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句