PowerShell: Cast Object Type

If you load an CSV file with import-csv you will end up with an object of type System.Management.Automation.PSCustomObject. It’s an array.

In such a case I liked to use such an imported file or especially the imported data with the correct object type.

Therefore I created an generic “cast” function in generic PowerShell that can be used for casting with other types.

See the following PowerShell script. The function “Get-CastedObject” takes to parameters:
1) the source array
2) the result object type as string

In the following sample the script creates a CSV file and reads the content of the file during the next run. After loading the data the objects of the array will be “casted” to the correct data type.

Therefore the cast function looks for the “property” object members and tries to assign them to the new created object of the expected result type.

I’m sure there are several opportunities for improvements. Please let me know!

$outfile = C:tempcast-test.csv

Add-Type @’
public class ResultObj
{
public string Test1 = “”;
public string Test2 = “”;
public bool   Test3 = false;
public int    Test4 = 0;
}
‘@

function Get-CastedObject
{
param(
[Parameter(Mandatory
=$true)] [object]$inputObject = $null,
[Parameter(Mandatory
=$true)] [string]$resultType = $null)

if($inputObject -isnot [System.Management.Automation.PSCustomObject] ) {
return $null
}

if($resultType -eq $null ) {
return $null
}

$resultObject = new-object $resultType

$inputObject |gm | ? {$_.MemberType -eq NoteProperty } |% {
Invoke-Expression $(`$resultObject.+$_.Name+ = `$inputObject.+$_.Name )
}

$resultObject
}

$ErrorActionPreference = Continue

if( @(get-childitem $outfile).count -gt 0 )
{
$global:imp = (Import-Csv -Delimiter ; -Path $outfile )
}

$l = @();

$imp | % {$l = $l + (Get-CastedObject $_ ResultObj)  }

$r = New-Object System.Random

for($i=0;$i -lt 10;$i++ ){
$obj = New-Object ResultObj
$obj.Test1 = Test + $l.Count.ToString()
$obj.Test2 = ([System.DateTime]::Now).ToString(HH:mm:ss)
$obj.Test3 = &{if( ($r.NextDouble())-lt 0.5 ) {$true }else {$false } }
$obj.Test4 = [int]$r.Next()
$l = $l + $obj
}

del $outfile -ErrorAction SilentlyContinue
$l |Export-Csv -Delimiter ; -Path $outfile -Encoding utf8 -Force -NoTypeInformation

Please notice my disclaimer in the right sidebar!

Leave a Reply

Your email address will not be published. Required fields are marked *