21

I am trying to get a recursive list of files in a particular subfolder structure, then save them to a table so that I can use a foreach loop to work with each row. I have the following code:

$table = get-childitem -recurse | where {! $_.PSIsContainer} | Format-Table Name, Length

foreach ($row in $table)
{
  $row[0]
  $row[1]
}

If I try to output $table as-is, it looks perfect, with two columns of data for all of the files. If I try and step through with foreach (like above), I get the "Unable to index into an object of type Microsoft.PowerShell.Commands.Internal.Format.FormatEndData." error message.

What am I doing wrong?

abatishchev
  • 98,240
  • 88
  • 296
  • 433

3 Answers3

35

I don't know why you're trying to step through formatted data at all. But as it is, $table is just a collection of strings. So you can do the following:

$table = get-childitem -recurse | where {! $_.PSIsContainer} | Format-Table Name, Length

foreach ($row in $table)
{
  $row
}

But I don't know why you'd want to. If you're trying to do something with the data in the file you could try this:

$files = get-childitem -recurse | where {! $_.PSIsContainer}
foreach ($file in $files)
{
    $file.Name
    $file.length
}
Dr1Ku
  • 2,875
  • 3
  • 47
  • 56
Chris N
  • 7,239
  • 1
  • 24
  • 27
  • What I am trying to do is create an array of data from the gci, then build a SQL table using a foreach loop and a series of "INSERT INTO" commands. Your second example got me exactly what I need. Thanks! –  Jul 19 '12 at 20:10
15

Never use any of the format commands until you are completely finished working with the data. The format commands convert everything to strings, so you lose the original objects.

$table = get-childitem -recurse | where {! $_.PSIsContainer}
foreach($file in $table){
    $file.Name
    $file.FullName
}
EBGreen
  • 36,735
  • 12
  • 65
  • 85
  • 3
    For what it's worth, this gotcha comes up enough that I'm sure there is a dupe question out there somewhere. I didn't see one quickly. If someone comes across it, post and I will get the close votes started. – EBGreen Jul 19 '12 at 20:00
1

I was cleaning up some profiles just a moment ago and found this post during my process and thought I would share how I looped through the results of get-childitem(ls is just an alias of gci I think?). Hope this helps someone somewhere.

$blob = (ls).name 
foreach ($name in $blob) { 
get-childitem "D:\CtxProfiles\$name\Win2012R2v4\UPM_Profile\AppData\Local\Google\Chrome\User Data\Default\Default\Media Cache\f_*" -erroraction 'silentlycontinue'|remove-item -force -recurse -confirm:$false 
}