powershell - 将 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
}
解决方案
在转换为目标类型时,您可以使用哈希表文字作为初始值设定项:
# 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
}
推荐阅读
- arrays - 从 PostData 的 JSONObject 获取 JSONArray 时出错
- java - 为 Spring Profile 提供配置文件名称
- eclipse - Eclipse:在启动时启用与编辑器的链接
- c++ - 如何在 constexpr if-else 链中导致静态错误?
- scala - 有没有办法在 yaml 文件中应用条件并通过从 yaml 读取在 scala 中运行?提供一个简单的同文件yaml示例
- javascript - 在 javascript 中使用 toLocaleString 模块得到错误的结果
- node.js - 使用 azure DevOps 管道部署 Azure 函数应用
- python - 如何拆分括号内用逗号分隔的字符串
- reactjs - react-stripe-elements v1.1.0 createPaymentMethod 在 react 15.6.2 中不起作用
- facebook-graph-api - Facebook Graph API - 无权发布到群组