gpt4 book ai didi

c# - 在 C# cmdlet 中创建 PowerShell PSObject

转载 作者:太空狗 更新时间:2023-10-29 22:36:49 28 4
gpt4 key购买 nike

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() 来简单地反射(reflect) 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# - 在 C# cmdlet 中创建 PowerShell PSObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30985008/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com