对派生的 Cmdlet 的自定义实现会是什么样子感兴趣,真的想看看涉及多少工作。模拟了以下内容:
using System.Management.Automation;
namespace EMSEngineering
{
[Cmdlet(VerbsDiagnostic.Test, "Cmdlet")]
public class TestCmdlet : Cmdlet
{
static int nextIndex = 0;
private int index = nextIndex;
public TestCmdlet()
{
System.Console.WriteLine("instantiating {0}", index);
nextIndex++;
}
~ TestCmdlet()
{
System.Console.WriteLine("terminating {0}", index);
}
[Parameter(Mandatory = true, ValueFromPipeline = true)]
public string[] SomeParameter { get; set; }
protected override void BeginProcessing()
{
if (SomeParameter != null)
WriteVerbose(string.Format("begin processing {0} params", SomeParameter.Length));
}
protected override void ProcessRecord()
{
foreach (string param in SomeParameter)
WriteObject(string.Format("processing …Run Code Online (Sandbox Code Playgroud) 使用 Powershell,System.Management.Automation.Cmdlet.Invoke() 返回类型的对象'<Invoke>d__40'而不是指定的 OutputType。
重现:
powershell -NoProfileAdd-Type -Path .\ExampleCmdlet.cs$command = [SendGreeting.SendGreetingCommand]::new()$command.Name = 'Person'$invoke = $command.Invoke()$invoke.GetType()预期:[string]
实际:[<Invoke>d__40]
$PS版本表:
Name Value
---- -----
PSVersion 5.1.19041.1237
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.19041.1237
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
Run Code Online (Sandbox Code Playgroud)
Get-Member -InputObject $invoke揭示这个来实现IEnumerator和一些玩弄.MoveNext(),.Current有时会输出预期的"Hello Person!"结果。
这是什么<Invoke>d__40类型?
为什么$command.Invoke()不直接返回预期的字符串输出?