Question:
I’m pretty new to powershell, so I won’t be surprised at all if I’m going about this all wrong. I’m trying to create a function that, when executed, prints results formatted as a table. Maybe it would even be possible to pipe those results to another function for further analysis.
Here’s what I have so far. This is a simple function that iterates through a list of paths and collects the name of the directory and the number of items in that directory, putting the data in a hashtable, and returning an array of hashtables:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
function Check-Paths(){ $paths = "C:\code\DirA", "C:\code\DirB" $dirs = @() foreach ($path in $paths){ if (Test-Path $path){ $len = (ls -path $path).length } else{ $len = 0 } $dirName = ($path -split "\\")[-1] $dirInfo = @{DirName = $dirName; NumItems = $len} $dirs += $dirInfo } return $dirs } |
That seems straightforward enough. However, when I go run the command, this is what I get:
1 2 3 4 5 6 7 8 9 |
PS > Check-Paths Name Value ---- ----- DirName DirA NumItems 0 DirName DirB NumItems 0 |
What I want is this:
1 2 3 4 5 |
DirName NumItems ------- -------- DirA 0 DirB 0 |
I could just hack my function to use a write
statement, but I think there must be a much better way to do this. Is there a way to get the data formatted as a table, even better if that can be such that it can be piped to another method?
Answer:
How ’bout using
1 2 |
return new-object psobject -Property $dirs |
That would return an object whose properties match the items in the hashtable. Then you can use the built-in powershell formatting cmdlets to make it look like you want. since you only have 2 properties, it will be formatted as a table by default.
EDIT: Here’s how the whole thing would look (After the various suggestions):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function Check-Paths(){ $paths = "C:\code\DirA", "C:\code\DirB" $dirs = @() foreach ($path in $paths){ if (Test-Path $path){ $len = (ls -path $path).length } else{ $len = 0 } $dirName = ($path -split "\\")[-1] new-object psobject -property @{DirName = $dirName; NumItems = $len} } } |