powershell - 如何将带有附加 Prop 的PSCustomObject转换为自定义类

标签 powershell powershell-5.0 pscustomobject

在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/

相关文章:

powershell - 是否可以在 PowerShell 中使用带有嵌套哈希表的 splatting?

powershell - 设置系统有权通过Powershell写入文件夹

powershell - 为什么添加到 ArrayList 会计算传递给它的内容?

powershell - 有条件地替换 PowerShell 对象中的值

powershell - ExpandProperty - 管道中缺少的对象

c# - 添加依赖于第一个类型的第二个类型时出错

windows - PowerShell FTP 上传不工作 - 创建零字节文件

powershell - 您必须在 '/' 运算符的右侧提供一个值表达式

powershell - 重命名时跳过具有给定前缀的文件

powershell - 为数组中的所有对象转换属性的数据类型