0

I'm trying to cast output from Get-Content myfile.txt into an ArrayList object so that I can easily insert and change strings with .add and .insert. What I've tried is

[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  

if I just assign $mylist=Get-Content myfile.txt it will change data type to static array which I don't want

1
  • Get-Content myfile | ForEach-Object {$mylist.Add($_)} you need to actually pass a value to Add method? Commented Jan 18, 2017 at 13:02

1 Answer 1

5

Get-Content returns an array, so you can cast directly to an ArrayList:

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

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

Now you can modify with the .add() or .insert() methods like:

$mylist.insert(2,"new content")
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.