在C#cmdlet中创建PowerShell PSObject

C#的新手,但在PowerShell中经验丰富.接管别人的代码.编写已编译的PowerShell模块,并尝试根据返回的数据确定如何创建对象.现在,代码返回一个字符串:ServerResponseUCCSiteModel requestModel = this.MakeRequest(...

C#的新手,但在PowerShell中经验丰富.接管别人的代码.编写已编译的PowerShell模块,并尝试根据返回的数据确定如何创建对象.现在,代码返回一个字符串:

ServerResponse<UCCSiteModel> requestModel = this.MakeRequest("/site/api/", "site", "GET", this.Credentials, queryString);
StringBuilder builder = new StringBuilder();

if (requestModel != null && requestModel.Response != null)
{
    builder.AppendLine("SiteID: " + requestModel.Response.SiteID);
    builder.AppendLine("Identity: " + requestModel.Response.SiteName);
    builder.AppendLine("Site Code: " + requestModel.Response.SiteCode);
    builder.AppendLine("Contact Name: " + requestModel.Response.ContactName);
    builder.AppendLine("Contact Number: " + requestModel.Response.ContactNumber);
    builder.AppendLine("Contact Email Address: " + requestModel.Response.ContactEmailAddress);
    builder.AppendLine("Address: " + requestModel.Response.Address);
    builder.AppendLine("City: " + requestModel.Response.City);
    builder.AppendLine("State: " + requestModel.Response.State);
    builder.AppendLine("Post Code: " + requestModel.Response.PostCode);
    builder.AppendLine("Time Zone: " + requestModel.Response.Timezone);
    builder.AppendLine("Longitude: " + requestModel.Response.longitude);
    builder.AppendLine("Latitude: " + requestModel.Response.latitude);                    
    this.WriteResponse(requestModel, builder.ToString());
}

如何从requestModel.Response创建一个对象以发送回PowerShell而不是字符串?在编写PowerShell时,我通常会使用New-Object PsObject,然后使用Add-Member.不知道如何在C#中做到这一点,或者它被称为什么(所以我可以搜索).任何人?

解决方法:

您可以通过在PSObject的Members属性上调用Add()来镜像Add-Member的行为(为了便于在PowerShell中访问,我会将属性名称更改为CamelCase):

if (requestModel != null && requestModel.Response != null)
{
    PSObject responseObject = new PSObject();

    responseObject.Members.Add(new PSNoteProperty("SiteID", requestModel.Response.SiteID));
    responseObject.Members.Add(new PSNoteProperty("Identity", requestModel.Response.SiteName));
    // and so on etc... 
    responseObject.Members.Add(new PSNoteProperty("Latitude", requestModel.Response.latitude));

    this.WriteObject(responseObject);
}

本文标题为:在C#cmdlet中创建PowerShell PSObject

基础教程推荐