问题描述
受到这些问题的启发:
- Get a specific octet from the string representation of an IPv4 address
- Powershell - Checking IP Address range based on CSV file
我正在尝试使用PowerShell中的ToBigInt()
方法扩展IPAddress
类(如果可能的话),以便能够使用以下方法轻松比较(IPv4 和 IPv6)地址比较操作以及-lt
和-gt
。例如:
([IPAddress]'2001:db8::8a2e:370:7334').ToBigInt() -lt ([IPAddress]'2001:db8::8a2e:370:7335').ToBigInt()
我的第一次尝试:
class IPAddress : System.Net.IPAddress {
[Void]ToBigInt() {
$BigInt = [BigInt]0
foreach ($Byte in $This.GetAddressBytes()) {
$BigInt = ($BigInt -shl 8) + $Byte
}
$BigInt
}
}
导致错误:
Line | 1 | class IPAddress : System.Net.IPAddress { | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | Base class 'IPAddress' does not contain a parameterless constructor.
因此,显然,我需要将([IPAddress]::new
)构造函数添加到子类中:
class IPAddress : System.Net.IPAddress {
IPAddress ([long]$NewAddress) : base($NewAddress) { }
IPAddress ([byte[]]$Address,[long]$ScopeId) : base($Address,$ScopeID) { }
IPAddress ([System.ReadOnlySpan[byte]]$Address,$ScopeID) { }
IPAddress ([byte[]]$Address) : base($Address) { }
IPAddress ([System.ReadOnlySpan[byte]]$Address) : base($Address) { }
[Void]ToBigInt() {
$BigInt = [BigInt]0
foreach ($Byte in $This.GetAddressBytes()) {
$BigInt = ($BigInt -shl 8) + $Byte
}
$BigInt
}
}
现在,类定义已被接受,但是当我尝试创建IPAddress
时,例如:
[IPAddress]'172.13.23.34'
我收到一个新错误:
OperationStopped: Unable to cast object of type 'System.Net.IPAddress' to type 'IPAddress'.
如何解决此投射错误?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)