0

Im writing a powershell script which prints disk information from computers from AD OU. My function looks like this:

function Get-DiskInfo {
    $disk = Get-WMIObject Win32_Logicaldisk -ComputerName $computer |
            Select DeviceID,
            @{Name="SizeGB";Expression={$_.Size/1GB -as [int]}},
            @{Name="FreeGB";Expression={[math]::Round($_.Freespace/1GB,2)}}
            Write-Host $Computer "Disks: "$disk

if i would run that Get-WMIObject against a single computer i get the following output:

DeviceID SizeGB FreeGB
-------- ------ ------
C:          953 757,08

But if i run the function against multiple computers the printout looks like this:

Disks:  @{DeviceID=C:; SizeGB=214; FreeGB=21,83} @{DeviceID=D:; SizeGB=932; FreeGB=740,09} @{DeviceID=E:; SizeGB=0; FreeGB=0}

Im farely new to powershell so is there something i should be doing differently to get the output look nicer

Whole script: https://gist.github.com/ErkkaKorpi/f1b10a62ac79763fa38082b6c25e8f1b

1 Answers1

1

The problem is, that by using this output:

Write-Host $Computer "Disks: "$disk

PowerShell creates a string interpretation of the $disk object.

If you change this to:

Write-Host $Computer
$disk

You get the output you want.


To further improve this:

function Get-DiskInfo {
    Get-WMIObject Win32_Logicaldisk -ComputerName $computer |
        Select @{Name="Computer";Expression={$computer}},
        DeviceID,
        @{Name="SizeGB";Expression={$_.Size/1GB -as [int]}},
        @{Name="FreeGB";Expression={[math]::Round($_.Freespace/1GB,2)}}
}

This will result in the computer name being part of the data:

Computer DeviceID SizeGB FreeGB
-------- -------- ------ ------
pc2542   C:          238  32,18
pc2542   P:          408  19,18
pc2542   U:         1475 293,41

This allows you to use further PowerShell cmdlets with this data, sorting, grouping, calculations etc.

Gerald Schneider
  • 19,757
  • 8
  • 52
  • 79
  • 1
    Or completely skip the write-host. – Zoredache Nov 22 '17 at 07:59
  • @ErkkaKorpi It is generally considered good practice to mark the answer as the accepted one, once you are satisfied. Helps everybody see that quickly, and rewards the person helping you (and you receive a small bit of rep as well) :) – Grigory Sergeev Nov 23 '17 at 10:50