你是对也是错 - 这完全取决于目标参数是否是值类型(例如System.DateTime 是一个结构) - 在这种情况下,在参数绑定期间类型强制会丢失所有内容。
但是,如果参数类型是引用类型,您可以使用 PSObject.AsPSObject()“复活”PSObject 包装器。
为了便于复制,我在纯 (-ish) PowerShell 中提出了以下示例,但我相信它充分说明了我的观点
将以下内容粘贴到 C# 源文件中(例如,TestCmdlets.cs):
using System;
using System.Management.Automation;
namespace TestPSObject
{
// This will be our parameter type
public class TestObject {}
// This will be our reference type test cmdlet
[Cmdlet(VerbsDiagnostic.Test, "PSObjectByRef")]
public class TestPSObjectByRefCommand : Cmdlet
{
[Parameter(Mandatory=true)]
public TestObject TestObject
{
get { return testObject; }
set { testObject = value; }
}
private TestObject testObject;
protected override void ProcessRecord()
{
// If this works, we should receive an object with
// identical psextended properties
WriteObject(PSObject.AsPSObject(this.TestObject));
}
}
// This will be our value type test cmdlet
[Cmdlet(VerbsDiagnostic.Test, "PSObjectByValue")]
public class TestPSObjectByValueCommand : Cmdlet
{
[Parameter(Mandatory=true)]
public DateTime DateTime
{
get { return dateTime; }
set { dateTime = value; }
}
private DateTime dateTime;
protected override void ProcessRecord()
{
// If this works, we should receive an object with
// identical psextended properties (hint: we won't)
WriteObject(PSObject.AsPSObject(this.DateTime));
}
}
}
现在,在您的 shell 中,编译并导入我们的测试模块:
Add-Type -Path .\TestCmdlets.cs -OutputAssembly TestPSObject.dll -OutputType Library
Import-Module .\TestPSObject.dll
接下来我们创建我们的测试主题并为它们添加一个 note 属性:
$TestObject = New-Object TestPSObject.TestObject
$TestObject |Add-Member -MemberType NoteProperty -Name TestProperty -Value "Hi there!"
$DateTime = Get-Date
$DateTime |Add-Member -MemberType NoteProperty -Name TestProperty -Value "Hi there!"
当您取消引用 TestProperty 成员时,它们现在都返回字符串值 Hi there!。
现在进行实际测试:
$TestObjectAfter = Test-PSObjectByRef -TestObject $TestObject
$DateTimeAfter = Test-PSObjectByValue -DateTime $DateTime
这仍然会返回Hi there!:
$TestObjectAfter.TestProperty
但这不会:
$DateTimeAfter.TestProperty