1

从 C# 中的 PowerShell 主机返回的 PSObject 映射的最简单方法是什么?

示例程序(减去实际映射):

class SOResult
{
    public DateTime A { get; set; }
    public string B { get; set; }
}

var script = "@{ A = (Get-Date); B = 'Hello World' };";

var instance = PowerShell.Create();
instance.AddScript(script);

var invokeResult = instance.Invoke();

var psObject = invokeResult.First();
4

1 回答 1

0

这是迄今为止我发现的最好的方法。关键是.BaseObject在PSObject上访问,这会返回一个Hashtable,然后映射就相当简单了:

CreateMap<Hashtable, SOResult>()
    .ForMember(o => o.A, x => x.MapFrom(f => f["A"]))
    .ForMember(o => o.B, x => x.MapFrom(f => f["B"]));

完整的工作程序:

static void Main(string[] args)
{
    Mapper.Initialize(c => c.AddProfile<SOProfile>());

    var script = "@{ A = (Get-Date); B = 'Hello World' };";

    var instance = PowerShell.Create();
    instance.AddScript(script);

    var invokeResult = instance.Invoke();

    var psObject = invokeResult.First().BaseObject;

    var soResult = Mapper.Map<SOResult>(psObject);

    Debug.Assert(soResult != null && !string.IsNullOrWhiteSpace(soResult.B));
}


class SOProfile : Profile
{
    public SOProfile()
    {
        CreateMap<Hashtable, SOResult>()
            .ForMember(o => o.A, x => x.MapFrom(f => f["A"]))
            .ForMember(o => o.B, x => x.MapFrom(f => f["B"]));
    }

}

不幸的是,如果您有多个简单的属性,这将变得很痛苦,因为您需要反复将子属性从 PSObject 转换为 Hashtable。

于 2016-08-16T08:01:14.320 回答