How to display the output like a table

Viewed 42

How to display the output like a table. Currently the output is not like the table

$Count = @()
$Types = ('.jpg', '.png', '.tif', '.gif', '.jpeg', '.mp4', '.mov')
foreach ($Type in $Types) {
    $i = 0
    $Files = Get-ChildItem 'F:\'-Filter *$type -Recurse | Where-Object { !$_.PsIsContainer }
    [array]$Count += $Files.Count
    $i += 1
}
Write-Host $Types
Write-Host $Count

like this:

Type    Count
------ -------
jpg     100
png     200
1 Answers

Here is one way to do it using a hash table:

$Types = '.jpg', '.png', '.tif', '.gif', '.jpeg', '.mp4', '.mov'
$out   = @{}

foreach($Type in $Types) {
    foreach($file in Get-ChildItem 'F:\' -Filter *$type -Recurse -File) {
        $out[$file.Extension] += 1
    }
}

$out.GetEnumerator().ForEach{ [pscustomobject]@{ Type = $_.Key; Count = $_.Value } }

If you want to sort by highest to lowest you can use Sort-Object:

$out.GetEnumerator() | Sort-Object Value -Descending | ForEach-Object {
    [pscustomobject]@{ Type = $_.Key; Count = $_.Value }
}

Another alternative is to use Group-Object and -Include instead of -Filter:

$Types = '*.jpg', '*.png', '*.tif', '*.gif', '*.jpeg', '*.mp4', '*.mov', '*.ps1'
Get-ChildItem . -Include $Types -Recurse -File |
    Group-Object Extension -NoElement |
        ForEach-Object { [pscustomobject]@{ Type = $_.Name; Count = $_.Count } }
Related