.net - Powershell won't preserve the type cast when updating an object's property -
i have array of objects want sort on "device" property. challenge "device" property can ip or hostname. so, approach separate them array ips , name (strings).
the problem when cast device column net.ipaddress , save reverts string.
here doing:
$devicebyip = @() $devicebyhostname = @() foreach ($row in $data) { try { [net.ipaddress]$row.device = $row.device $devicebyip += $row } catch { #[string]$row.device | out-null $devicebyhostname += $row } }
when this: [net.ipaddress]$row.device = $row.device
reverts string. if this: $devicebyip | %{$_.device.gettype().fullname}
i see device property of objects system.string.
what doing wrong here?
you didn't mention type of object $row is, appears $row native .net object device exposed system.string. if don't have access source code of $row type, can use select-object replace each $row object pscustomtype object has same properties:
$devicebyip = @() $devicebyhostname = @() foreach ($row in $data) { try { $row = $row | select-object * [net.ipaddress]$row.device = $row.device $devicebyip += $row } catch { $devicebyhostname += $row } }
and if didn't want rely on exception handling, little bit costlier, use tryparse method of system.net.ipaddress:
$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 } }
Comments
Post a Comment