首页 > 解决方案 > 将 PSCustomObject 转换为 powershell 中的自定义类型

问题描述

有一个自定义类型,其定义如下:

class User
{
    public int Age { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

我必须将PSCustomObject具有以下属性的类型转换为User类型。

@{
    Age:12;
    FirstName:'John';
    LastName:'Snow';
    Address:'Whatev';
    Sex:'Male'
}

但是每当我尝试将 ps 对象转换为这样的自定义类型时:$john = [User]$psObj我得到InvalidCastConstructorException. 显然它出现是因为它具有比类型支持PsCustomObject的更多属性。User

问题是:我们是否有一种简单的方法可以将此类PSCustomObject数据转换为自定义类型?

PS我必须支持powershell 5.1

PSS 我见过类似的问题,但我的情况略有不同。我不限于函数参数列表中的显式转换

更新 我想出了下一个功能

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
}

标签: powershell

解决方案


在转换为目标类型时,您可以使用哈希表文字作为初始值设定项:

# Assuming your object looks like this ...
$object = [pscustomobject]@{
    Age       = 12
    FirstName = 'John'
    LastName  = 'Snow'
    Address   = 'Whatev'
    Sex       = 'Male'
}

# ... you can initialize the properties of a new instance by casting a dictionary like this
$target = [User]@{
  Age       = $object.Age
  FirstName = $object.FirstName
  LastName  = $object.LastName
}

推荐阅读