2

I want to create a Hashtable which groups files with the same name in arrays so I can later on work with those to list some properties of those files, like the folders where they're stored.

$ht = @{}
gci -recurse -file | % {
    try{
        $ht.Add($_.Name,@())
        $ht[$_.Name] += $_
    }
    catch{
        $ht[$_.Name] += $_
    }
}

All I'm getting is:

Index operation failed; the array index evaluated to null.
At line:8 char:13
+             $ht[$_.Name] += $_
+             ~~~~~~~~~~~~~~~~~~

I'm not sure why this isn't working, I'd appreciate any help.

1
  • if ($ht[$_.name]) { $ht[$_.name] += $_ } else { $ht[$_.name] = ,$_ } Commented Apr 23, 2017 at 19:28

1 Answer 1

2

Don't reinvent the wheel. You want to group files with the same name, use the Group-Object cmdlet:

$groupedFiles = Get-ChildItem -recurse -file | Group-Object Name

Now you can easy retrieve all file names that are present at least twice using the Where-Object cmdlet:

$groupedFiles | Where-Object Count -gt 1

You are getting this error because if your code hits the catch block, the current pipeline variable ($_) represents the last error and not the current item. You can fix that by either storing the current item an a variable, or you use the -PipelineVariable advanced cmdlet parameter:

$ht = @{}
gci -recurse -file -PipelineVariable item | %  {
    try{
        $ht.Add($item.Name,@())
        $ht[$item.Name] += $item
    }
    catch{
        $ht[$item.Name] += $item
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.