我可以以某种方式将`Get-Content` cmdlet输出到`ArrayList`对象中吗?

时间:2017-01-18 12:57:12

标签: powershell

我尝试将Get-Content myfile.txt的输出转换为ArrayList对象,以便我可以使用.add.insert轻松插入和更改字符串。我尝试过的是

[Systems.Collections.ArrayList]mylist=@()
Get-Content myfile | $mylist # obviously wrong
Get-Content myfile | ForEach-Object {$mylist} # don't quite grasp the logic, get empty array as a result
Get-Content myfile | ForEach-Object {$mylist.Add()} # get overload error  

如果我只是分配$mylist=Get-Content myfile.txt,它会将数据类型更改为我不想要的静态数组

1 个答案:

答案 0 :(得分:4)

Get-Content返回一个数组,因此您可以直接转换为ArrayList:

$mylist = [System.Collections.ArrayList](Get-Content myfile)
$mylist.gettype()                                                                                                                                                                                       

IsPublic IsSerial Name                                     BaseType                                                                                                                                        
-------- -------- ----                                     --------                                                                                                                                        
True     False    ArrayList                                System.Object

现在,您可以使用.add().insert()方法进行修改,例如:

$mylist.insert(2,"new content")