Powershell 如何将带有附加道具的PSCustomObject转换为自定义类
在PowerShell 5.1中,是否有一种简洁的方法将Powershell 如何将带有附加道具的PSCustomObject转换为自定义类,powershell,powershell-5.0,pscustomobject,Powershell,Powershell 5.0,Pscustomobject,在PowerShell 5.1中,是否有一种简洁的方法将PSCustomObject转换为自定义类作为函数参数? 自定义对象包含其他属性 我希望能够做到这样: class-MyClass{ [ValidateNotNullOrEmpty()][string]$PropA } $input=[pscustomobject]@{ 普罗帕=‘普罗帕’; AdditionalProp='AdditionalProp'; } 函数类型FTW{ [CmdletBinding()] param( [参数(必需
PSCustomObject
转换为自定义类作为函数参数?
自定义对象包含其他属性
我希望能够做到这样:
class-MyClass{
[ValidateNotNullOrEmpty()][string]$PropA
}
$input=[pscustomobject]@{
普罗帕=‘普罗帕’;
AdditionalProp='AdditionalProp';
}
函数类型FTW{
[CmdletBinding()]
param(
[参数(必需=$True,位置=0,ValueFromPipeline)][MyClass]$myObj
)
“成功!”
}
DuckTypingFtw$输入
不幸的是,不是成功了代码>,我得到:
DuckTypingFtw:无法对参数进行参数转换
“myObj”。无法转换值“@{PropA=PropA;
AdditionalProp=AdditionalProp}”以键入“MyClass”。错误:“不能
转换
键入“System.Management.Automation.PSCustomObject”以键入“MyClass”
在C:\temp\tmp.ps1:23字符:15
+DuckTypingFtw$输入
+ ~~~~~~
+CategoryInfo:InvalidData:(:)[DuckTypingFtw],参数BindingArgumentTransformationException
+FullyQualifiedErrorId:参数argumentTransformationError,DuckTypingFtw
如果我注释掉附加属性
,一切正常
基本上,我想要实现的是从一个函数返回一个对象并将其传递给第二个函数,同时确保第二个函数的param具有所有预期属性。在代码中,您为自定义对象定义了两个属性,但为类定义了一个属性。这就是为什么您需要:
- 要在类中添加
附加属性
- 要从PsCustomObject中删除
附加属性
通过设计,转换是不可能的。如果您为MyClass类创建了一个接受pscustomobject并通过属性的构造函数,那么它应该可以工作:
class MyClass {
MyClass([pscustomobject]$object){
$this.PropA = $object.PropA
}
[ValidateNotNullOrEmpty()][string]$PropA
}
$input = [pscustomobject]@{
PropA = 'propA';
AdditionalProp = 'additionalProp';
}
function DuckTypingFtw {
[CmdletBinding()]
param(
[Parameter(Mandatory = $True, Position = 0, ValueFromPipeline)] [MyClass] $myObj
)
'Success!'
}
DuckTypingFtw $input
编辑:
如果您还想在其他地方使用MyClass,请为MyClass添加默认构造函数,如:
class MyClass {
MyClass() { }
MyClass([pscustomobject]$object){
$this.PropA = $object.PropA
}
[ValidateNotNullOrEmpty()][string]$PropA
}
是的,这就是琐事,正如我所说:“如果我评论掉额外的道具,一切都很好。”。我仍然希望有一种方法-也许是自定义转换器?您可以定义一个像Map Property
这样的函数,它接受类和pscustomobject,并对它们使用反射,可能通过Get Member
和迭代属性。这样,您就可以匹配它们并忽略那些没有正确“映射”的。是的,但是DuckTypingFtw
是一个公共API,所以我不能期望消费者调用map属性。它需要透明…似乎唯一的方法是返回类的实例MyClass
,并且永远不要使用pscustomobject
。