Answered by:
GroupBy behaves awkward

Question
-
Hi.
I'm trying to get a listing of all files in a folder (and every sub-folder) grouped by directory. This is what I've got so far and which should work from my understanding:
Get-Childitem $Path -Recurse | Where {!$_.PsIsContainer} | Format-Table Name -GroupBy Directory
I'd expect that this outputs one table for each directory. But instead it does output one table for each file! I don't understand why this is happening, but I'm also new to PowerShell.
So here is an example of the output I'm getting:
Directory: C:\Users\Me\Desktop\Test Name ---- New Text Document (2).txt Directory: C:\Users\Me\Desktop\Test Name ---- New Text Document.txt
It outputs two tables despite it's the same folder. I especially don't understand it because the documentation says the following:
"You can also use the GroupBy parameter of the formatting cmdlets (such as Format-Table [m2] and Format-List [m2]) to group objects. Unlike Group-Object, which creates a single table with a row for each property value, the GroupBy parameters create a table for each property value with a row for each item that has the property value."
In case this is a bug in Format-Table could someone help me with a workaround?
I'd be very happy if someone could help me with this.
Thanks in advance,
PeterSunday, May 30, 2010 4:38 PM
Answers
-
Strange to me also, looks like 'Directory' value for each file is different. As a workaround I would suggest using DirectoryName instead. Latter is just string, and works as expected. 'Directory' is of System.IO.DirectoryInfo type and maybe that's the problem.
- Marked as answer by Shay Levi Monday, May 31, 2010 7:40 AM
Monday, May 31, 2010 6:05 AM
All replies
-
Strange to me also, looks like 'Directory' value for each file is different. As a workaround I would suggest using DirectoryName instead. Latter is just string, and works as expected. 'Directory' is of System.IO.DirectoryInfo type and maybe that's the problem.
- Marked as answer by Shay Levi Monday, May 31, 2010 7:40 AM
Monday, May 31, 2010 6:05 AM -
I agree with Bartek. In addition, you should also sort the results first if you don't want to have duplicated groups:
PS > help Format-Table -Parameter groupby
-GroupBy <Object>
Arranges sorted output in separate tables based on a property value. For example, you can use GroupBy to list services in separate tables based on their status.
Enter an expression or a property of the output. The output must be sorted before you send it to Format-Table .
(...)
Shay Levy [MVP]
http://blogs.microsoft.co.il/blogs/ScriptFanatic
PowerShell Toolbar- Proposed as answer by Aleksandar NikolićMVP Monday, May 31, 2010 8:52 AM
Monday, May 31, 2010 7:40 AM