在PowerShell 5.1中是否有一种巧妙的方法可以将PSCustomObject
转换为自定义类作为函数参数?
自定义对象包含其他属性。
我希望能够执行以下操作:
class MyClass {
[ValidateNotNullOrEmpty()][string]$PropA
}
$input = [pscustomobject]@{
PropA = 'propA';
AdditionalProp = 'additionalProp';
}
function DuckTypingFtw {
[CmdletBinding()]
param(
[Parameter(Mandatory = $True, Position = 0, ValueFromPipeline)] [MyClass] $myObj
)
'Success!'
}
DuckTypingFtw $input
不幸的是,我得到的不是
Success!
:DuckTypingFtw : Cannot process argument transformation on parameter 'myObj'. Cannot convert value "@{PropA=propA; AdditionalProp=additionalProp}" to type "MyClass". Error: "Cannot convert the "@{PropA=propA; AdditionalProp=additionalProp}" value of
type "System.Management.Automation.PSCustomObject" to type "MyClass"." At C:\temp\tmp.ps1:23 char:15 + DuckTypingFtw $input + ~~~~~~ + CategoryInfo : InvalidData: (:) [DuckTypingFtw], ParameterBindingArgumentTransformationException + FullyQualifiedErrorId : ParameterArgumentTransformationError,DuckTypingFtw
如果我注释掉
AdditionalProp
,一切正常。基本上,我要实现的是从一个函数返回一个对象并将其传递给第二个函数,同时确保第二个函数的参数具有所有预期的属性。
最佳答案
如果为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
}
关于powershell - 如何将带有附加 Prop 的PSCustomObject转换为自定义类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58330233/