I'm working on a PowerShell script that connects to our domain controllers and pulls information about the free and used space on the D: drive, where we've stored data like DFS shares. While I can gather the data correctly, the output comes in four lines for each domain controller, stacked vertically. I'm trying to format the output so that I can show three domain controllers on one line. I was thinking of putting each buffer into an array to create a three-column display, but I'm unsure how to do this. Here's a snippet of my code: the loop gathers data but I need help with formatting it into three columns at the end.
1 Answer
First off, make sure your formatting is clear. Instead of just dumping strings into your array, consider building custom objects for better structure. When you gather the disk info, create an object for each domain controller with the relevant properties. This way, you can easily format them in three columns using `Format-Table` or similar commands. Here's a better approach:
```powershell
$Disks = foreach($DC in $AllDCs){
$Disk = Get-CimInstance Win32_LogicalDisk -ComputerName $DC.Name -Filter "DeviceID='D:'"
if($Disk){
[pscustomobject]@{
Name = $DC.Name
"Total Space" = '{0:F2} GB' -f ($Disk.Size / 1GB)
"Percent Free" = '{0:P2}' -f ($Disk.FreeSpace / $Disk.Size)
}
} else {
[pscustomobject]@{
Name = $DC.Name
"Total Space" = 'N/A'
"Percent Free" = 'N/A'
}
}
}
$Disks | Format-Table -AutoSize
```
This will present a clean output in columns!
Thanks for this! I'm transitioning from C++ and BASH, and I'm still getting used to how PowerShell handles objects. Your suggestion really clears things up for me. I’ll definitely give this a try!