How to use a Select-Object to create your custom object array for you
Often when I am creating custom data, I usually:
  1. 1.
    run a query to get the data I want
  2. 2.
    iterate through that returned list and create new objects
  3. 3.
    add these objects to a separate array holder
  4. 4.
    return that.
You can merge this with something like:
1
$drives = [System.IO.DriveInfo]::GetDrives() |
2
Where-Object {$_.TotalSize} |
3
Select-Object @{Name='Name'; Expr={$_.Name}},
4
@{Name='Label'; Expr={$_.VolumeLabel}},
5
@{Name='Size(GB)'; Expr={[int32]($_.TotalSize / 1GB)}},
6
@{Name='Free(GB)'; Expr={[int32]($_.AvailableFreeSpace / 1GB)}},
7
@{Name='Free(%)'; Expr={[math]::Round($_.AvailableFreeSpace / $_.TotalSize,2)*100}},
8
@{Name='Format'; Expr={$_.DriveFormat}},
9
@{Name='Type'; Expr={[string]$_.DriveType}},
10
@{Name='Computer'; Expr={$ComputerName}}
11
12
$drives | ConvertTo-Json -Compress
Copied!
Saves time and makes the code faster and more readable!
Credit for the above code is here.
Copy link