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
基础教程推荐
猜你喜欢
- C#类和结构详解 2023-05-30
- C#控制台实现飞行棋小游戏 2023-04-22
- unity实现动态排行榜 2023-04-27
- winform把Office转成PDF文件 2023-06-14
- C# List实现行转列的通用方案 2022-11-02
- C# windows语音识别与朗读实例 2023-04-27
- 一个读写csv文件的C#类 2022-11-06
- C# 调用WebService的方法 2023-03-09
- linux – 如何在Debian Jessie中安装dotnet core sdk 2023-09-26
- ZooKeeper的安装及部署教程 2023-01-22