PowerShell - 实例化 IPAddressCollection

PowerShell - Instantiate IPAddressCollection

我正在尝试创建一个 [System.Net.NetworkInformation.IPAddressCollection] 对象来存储多个 [System.Net.IPAddress] 对象。

理想情况下,我想实现类似于以下内容:

$IPAddresses = [System.Net.NetworkInformation.IPAddressCollection]::new()
foreach ($target in [System.IO.File]::ReadLines($file)) {
    IPAddresses .Add([System.Net.IPAddress]::Parse($target))
}

我知道我可以更容易地实现,但为了提高我对 .Net/PowerShell 的理解,我想知道如何创建 [System.Net.NetworkInformation.IPAddressCollection] 的实例。

谢谢

你的类型加速器太复杂了。

$Collection = @()
ForEach ($IP in @(Get-Content -Path $file))
{
    $Collection += @([System.Net.IPAddress]$IP)
}

$Collection

你最终得到 [System.Net.IPAddress[]] 类型 $Collection


@Bill_Stewart进一步缩短:

$collection = Get-Content -Path $file | ForEach-Object { [IPAddress] $_ }