如何向自定义对象数组添加条目

时间:2017-11-21 13:38:01

标签: powershell csv

我正在将CSV文件导入PScustomobject数组,该数组包含4列,需要在脚本中进一步向对象添加条目。

当我尝试这样做并将数据放入列中时,我得到了令人愉快的响应:无法找到“添加”的重载和参数计数:“4”。

代码的简化版本:

 $Localadmins = import-csv "c:\admins.csv"
    $LocalAdmins

    Scope  Admin      Server    Type      
    -----  -----      ------    ----      
    Domain John.Smith SRV-SQL01 LocalAdmin
    Local  svc_sql    SRV-SQL01 LocalAdmin

    $LocalAdmins.Add("Domain", "Frank.Zappa", "SRV-SQL01", "LocalAdmin")

> Cannot find an overload for "Add" and the argument count: "4".
> 
> At line:1 char:16

2 个答案:

答案 0 :(得分:3)

也许这可以帮助你,评论中的解释。可以将其粘贴到PowerShell ISE中,以便在调试时看到会发生什么。

# Simulate $Localadmins = import-csv "c:\admins.csv" $Local Admins
$Localadmins = @"
Scope, Admin, Server, Type
Domain, Frank.Zappa, SRV-SQL01, LocalAdmin
Domain, Led-Zeppelin, SRV-02, LocalAdmin
"@ | ConvertFrom-Csv

# See what is possible with the object
# Notice there is no 'Add' method available

$Localadmins | Get-Member

<#
   TypeName: System.Management.Automation.PSCustomObject

Name        MemberType   Definition                     
----        ----------   ----------                     
Equals      Method       bool Equals(System.Object obj) 
GetHashCode Method       int GetHashCode()              
GetType     Method       type GetType()                 
ToString    Method       string ToString()              
Admin       NoteProperty System.String Admin=Frank.Zappa
Scope       NoteProperty System.String Scope=Domain     
Server      NoteProperty System.String Server=SRV-SQL01 
Type        NoteProperty System.String Type=LocalAdmin 
#>

# Add one user
$Localadmins += [PSCustomObject]@{
    Scope = 'Domain'
    Admin = 'Chuck-Norris'
    Server = 'MyServer'
    Type = 'LocalAdmin'
}

# Add another group of users by using an array
# and adding that array to the original one

$ExtraArray = @"
Scope, Admin, Server, Type
Domain, UserA, PC01, LocalAdmin
Domain, UserB, PC02, LocalAdmin
"@ | ConvertFrom-Csv

$Localadmins += $ExtraArray

$Localadmins

答案 1 :(得分:2)

我会选择:

getName(e:Event){
   const value:number =  parseInt((<HTMLSelectElement>event.srcElement).value);
   console.log((<HTMLSelectElement>event.srcElement.options[selectedIndex]text))
  }

因此,您需要创建新的 $Localadmins = import-csv "c:\admins.csv" $newRow = New-Object PsObject -Property @{ Scope = 'Domain' ; Admin = 'Frank.Zappa'; Server 0 'SRV-SQL01'; Type = 'LocalAdmin' } $Localadmins += $newRow 并通过PsObject运算符添加它。

希望有所帮助。