更新对象的属性时,Powershell不会保留类型转换

时间:2014-05-30 20:22:14

标签: .net powershell

我有一系列对象,我想对他们的"设备"进行排序。属性。挑战在于"设备"属性可以是IP或主机名。所以,我的方法是将它们分成带有IP的数组和另一个名称(字符串)的数组。

问题在于,当我将Device列转换为Net.IPAddress并将其保存回来时,它将恢复为字符串。

这是我正在做的事情:

$DeviceByIP = @()
$DeviceByHostname = @()
foreach ($row in $data) {
    try {
        [Net.IPAddress]$row.Device = $row.Device
        $DeviceByIP += $row
    } catch {
        #[string]$row.Device | out-null
        $DeviceByHostname += $row
    }
}

当我这样做时:[Net.IPAddress]$row.Device = $row.Device它会恢复为字符串。所以,如果我这样做: $ DeviceByIP | %{$ _。Device.GetType()。全称}

我看到对象的Device属性都是System.String。

我在这里做错了什么?

3 个答案:

答案 0 :(得分:1)

你不想这样做:

$DeviceByIP += [Net.IPAddress]$row.Device

我猜测列类型是一个字符串,因此更改单个行可能不会飞......

答案 1 :(得分:0)

BTW 如果的IP地址是[Net.IPAddress]类型,而不仅仅是一个带有IP地址的字符串,则不必依赖InvalidCastExceptions。您可以检查类似的类型:

if ($row.Device -is [Net.IPAddress]) {
   $DeviceByIP += $row.Device
}
else if ($row.Device -is [string]) {
   $DeviceByHostname += row.Device
}
else { Write-Error "Oops" }

答案 2 :(得分:0)

您没有提到$ row的对象类型,但看起来$ row是一个本机.NET对象,其中Device公开为System.String。如果您无权访问$ row类型的源代码,则可以使用Select-Object将每个$ row对象替换为具有相同属性的PSCustomType对象:

$DeviceByIP = @()
$DeviceByHostname = @()
foreach ($row in $data) {
    try {
        $row = $row | Select-Object *
        [Net.IPAddress]$row.Device = $row.Device
        $DeviceByIP += $row
    } catch {
        $DeviceByHostname += $row
    }
}

如果你不想依赖异常处理,这有点贵,你可以使用System.Net.IPAddress的TryParse方法:

$DeviceByIP = @()
$DeviceByHostname = @()
$ipAddress = $null
foreach ($row in $data) {
    $row = $row | Select-Object *
    if ([Net.IPAddress]::TryParse($row.Device, [ref]$ipAddress)) {
        $row.Device = $ipAddress
        $DeviceByIP += $row
    } else {
        $DeviceByHostname += $row
    }
}
相关问题