这是迄今为止我发现的最好的方法。关键是.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。