Reputation: 397
I am getting stuck here:
$file = gci C:\...\test\ | %{$_.name}
for ($i=0; $i -lt 100; $i++) {
$array_$i = gc C:\...\test\$($file[$i])
}
I am just trying to create multiple arrays for each text file in the directory.
Everything is working fine except the array name being declared - $array_$i
.
Upvotes: 1
Views: 3458
Reputation: 200523
Personally, I would pick one of the suggestions already presented. Using some kind of collection data structure usually greatly simplifies handling a number of distinct, but similar items.
Create an array of arrays:
$array = @()
Get-ChildItem C:\...\test | Select-Object -First 100 | ForEach-Object {
$array += ,@(Get-Content $_.FullName)
}
Running the Get-Content
call in an array subexpression and prepending it with the unary comma operator ensures that you append a nested array instead of each element being appended individually:
[
[ 'foo', 'bar', ... ],
[ 'baz', ... ],
...
]
rather than
[
'foo',
'bar',
'baz',
...
]
Create a hashtable of arrays:
$ht = @{}
Get-ChildItem C:\...\test | Select-Object -First 100 | ForEach-Object {
$ht[$_.Name] = Get-Content $_.FullName
}
Using a hashtable is preferable if you need to be able to look up content by a particular key (in this example the filename) instead of an index.
{
'something': [ 'foo', 'bar', ... ],
'other': [ 'baz', ... ],
...
}
Note that you'll have to choose a different key if you have duplicate filenames, though (e.g. in different subfolders).
If, however, for some reason you must create individual variables for each content array you can do so with the New-Variable
cmdlet:
$i = 0
Get-ChildItem C:\...\test | Select-Object -First 100 | ForEach-Object {
New-Variable -Name "array_$i" -Value (Get-Content $_.FullName)
$i++
}
Upvotes: 1
Reputation:
you can use this script easy to add your file in your array :
$array =New-Object System.Collections.ArrayList
dir c:\testpath | %{$content = gc $_.FullName;$array.Add($content) > $null}
Upvotes: 2
Reputation: 175085
PowerShell doesn't support variable variables (like php
for example).
Use a hash table instead:
$files = gci C:\...\test\ | % {$_.Name}
$fileArrays = @{}
for ($i=0;$i -lt $files.Count; $i++){
$fileArrays[$i] = gc C:\...\test\$($file[$i])
}
Depending on what the purpose is, I would probably use the file name as the key instead. You're routine can also be simplified by:
$fileArrays = @{}
Get-ChildItem C:\...\test\ |ForEach-Object {
$fileArrays[$_.Name] = Get-Content $_.FullName
}
Upvotes: 2