在Powershell中向数组添加自定义对象

时间:2016-06-10 05:43:59

标签: powershell

我想将一个带有如下属性的自定义对象添加到powershell数组中。我已经尝试了各种选项,但无法获得对数组添加此类对象的正确语法。我使用的是Powershell V2。请帮忙。

PS C:\Windows\system32> $executemultiplerequest | Get-member


   TypeName: Microsoft.Xrm.Sdk.Messages.ExecuteMultipleRequest

Name          MemberType            Definition
----          ----------            ----------
Equals        Method                bool Equals(System.Object obj)
GetHashCode   Method                int GetHashCode()
GetType       Method                type GetType()
ToString      Method                string ToString()
Item          ParameterizedProperty System.Object Item(string parameterName) {get;set;}
ExtensionData Property              System.Runtime.Serialization.ExtensionDataObject ExtensionData {get;set;}
Parameters    Property              Microsoft.Xrm.Sdk.ParameterCollection Parameters {get;set;}
RequestId     Property              System.Nullable`1[[System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, Publ...
RequestName   Property              System.String RequestName {get;set;}
Requests      Property              Microsoft.Xrm.Sdk.OrganizationRequestCollection Requests {get;set;}
Settings      Property              Microsoft.Xrm.Sdk.ExecuteMultipleSettings Settings {get;set;}

添加我尝试的选项:

以下是我试过的样本:

$item = New-Object System.Object
$item | Add-Member -MemberType Method -Name Equals $executemultiplerequest.Equals -MemberType Property $executemultiplerequest.ExtensionData
$array += item

甚至在我进入数组存储之前,我收到了一个错误。 Add-Member行收到错误:

Add-Member : Cannot add a member with type "Method". Specify a different type for the MemberTypes parameter. 

1 个答案:

答案 0 :(得分:1)

我不确定您使用的类型,但如果您想

$item = New-Object psobject
$item | Add-Member -MemberType NoteProperty -Name RequestName -Value 'some string here'
$item | Add-Member -MemberType ScriptMethod -Name Multiply -Value {param($x,$y);$x * $y }
$item | Add-Member -MemberType ScriptProperty -Name RequestName1 -Value { Get-Service -Name BITS }

详细了解Add-member here