Grz*_*lko 5 powershell pscustomobject powershell-5.0
有没有一种巧妙的方法可以将 a 转换PSCustomObject为自定义类作为 PowerShell 5.1 中的函数参数?自定义对象包含附加属性。
我希望能够做这样的事情:
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
Run Code Online (Sandbox Code Playgroud)
不幸的是Success!,我得到的不是:
DuckTypingFtw:无法处理参数“myObj”的参数转换。无法将值“@{PropA=propA;AdditionalProp=additionalProp}”转换为类型“MyClass”。错误:“无法转换”@{PropA=propA; “AdditionalProp=additionalProp}”
类型“System.Management.Automation.PSCustomObject”的值要键入“MyClass”。在 C:\temp\tmp.ps1:23 字符:15 + DuckTypingFtw $input + ~~~~~~ + CategoryInfo : InvalidData: (:) [DuckTypingFtw], ParameterBindingArgumentTransformationException + ExcellentQualifiedErrorId : 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
Run Code Online (Sandbox Code Playgroud)
编辑:如果您还想在其他地方使用 MyClass,请为 MyClass 添加默认构造函数,例如:
class MyClass {
MyClass() { }
MyClass([pscustomobject]$object){
$this.PropA = $object.PropA
}
[ValidateNotNullOrEmpty()][string]$PropA
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1747 次 |
| 最近记录: |