Create Table with Variables in PowerShell Create Table with Variables in PowerShell powershell powershell

Create Table with Variables in PowerShell


Format-Table works best when you have all the data of interest in a single type of object. I would recommend creating custom objects for this e.g.:

foreach($computer in $computers){    $drives = Get-WmiObject -ComputerName $computer Win32_LogicalDisk | Where-Object {$_.DriveType -eq 3}    foreach($drive in $drives)    {        $obj = new-object psobject -Property @{                   ComputerName = $computer                   Drive = $drive.DeviceID                   Size  = $drive.size / 1GB                   Free  = $drive.freespace / 1GB                   PercentFree = $drive.freespace / $drive.size * 100               }        if ($obj.PercentFree -lt 10) {            $obj | Format-Table ComputerName,Drive,Size,Free,PercentFree            $i++        }    }}

If you want to change the display format then in the format-table command you can do this:

$obj | Format-Table ComputerName,Drive,@{n='Size';e={'{0:N1}' -f $_.Size}},Free,PercentFree


Keith has it covered, but as my reply was half written anyway, here it is. My version needs no new objects to be created and has the filtering as part of the pipeline.

As Keith says, keep everything as an object until the last minute. If you need to force PowerShell to format, use 'out-string'.

Also, look out for support for lists. Many commands will take a list as a parameter (e.g. list of computer names, email recipients) without the need for for-each loops. This can make code more concise, but arguably less readable, especially for a beginner. Anyway, here's what I cooked up:

$comps=@("server1","server2","server3","server4")$smtpServer = "mail.mydomain.com"$toList = @("someone@mydomain.com","anotherperson@mydomain.com")$minPercent = 10$tableSpec = @(        @{label="Computer";expression={$_.SystemName}},        @{label="Disk";expression={$_.DeviceID}},        @{label="Size Gb";expression={[int]($_.size / 1Gb)}},        @{label="PercentFree";expression={[int]($_.FreeSpace / $_.Size * 100)}}    )$report = (    Get-WmiObject -ComputerName $comps -Class Win32_LogicalDisk |    Where-Object { ($_.DriveType -eq 3) -and ($_.FreeSpace -lt ($_.Size * $minPercent / 100)) } |    Sort-Object SystemName, DeviceID |    ft -property $tableSpec -AutoSize |    Out-String    )Send-MailMessage -Body $report -To $toList -Subject "Disk space report" -SmtpServer $smtpServer