There is a custom type, which is defined like:
class User
{
public int Age { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
I have to convert the PSCustomObject
which has the following properties to the User
type.
@{
Age:12;
FirstName:'John';
LastName:'Snow';
Address:'Whatev';
Sex:'Male'
}
But whenever I try to cast the ps object to the custom type like this: $john = [User]$psObj
I get InvalidCastConstructorException
. Obviously it appears because the PsCustomObject
has many more properties then the User
type supports.
The question is: do we have an easy way to convert such PSCustomObject
data to custom type?
P.S. I have to support powershell 5.1
P.S.S I've seen similar issue, but I have a slightly different case. I'm not limited to the explicit conversion in the function parameters list
UPDATE I came up with the next function
function Convert-PSCustomObjectToCustomType {
param (
[System.Reflection.TypeInfo]$customType,
[PSCustomObject]$psCustomObj
)
$validObjProperties = @{}
$customObjProperties = $customType.GetProperties() | ForEach-Object { $_.Name }
foreach ($prop in $psCustomObj.PSObject.Properties) {
if ($customObjProperties -contains $prop.Name) {
$validObjProperties.Add($prop.Name, $prop.Value)
}
}
return New-Object -TypeName $customType.FullName -Property $validObjProperties
}