PowerShell local disk property no output

121 views Asked by At

I am building report for disk but need help, please. Here is the code:

$outputs = @()
$disks = get-wmiobject -class "Win32_LogicalDisk" -Filter 'driveType=3' -namespace "root\CIMV2"
foreach ( $disk in $disks ) {
    $output = New-Object PSObject -Property @{
        deviceID     = $disk.caption
        FileSystem   = $disk.fileSystem
        FreeSpace    = $disk.freeSpace/1GB
        Size         = $disk.size/1GB
        VolumeName   = $disk.volumeName

        used = "{0:N1}" -f ((("{0:N1}" -f ($disk.size/1gb)).ToString().replace(",",".") - ("{0:N1}" -f ($disk.freespace/1gb)).ToString().replace(",","."))   /   ("{0:N1}" -f ($disk.size/1gb)).ToString().replace(",",".") * 100)

        used2 = $used
    }
    $outputs += $output
}
$outputs | select deviceID, VolumeName, size, used, used2  | Format-Table

Everything is fine, but nothing in variable used2

deviceID VolumeName             Size used used2
-------- ----------             ---- ---- -----
C:       win        49,1992149353027 87,4
D:       data       170,701168060303 70,7
1

There are 1 answers

0
alroc On BEST ANSWER

$used doesn't exist as a variable in that scope, so used2 is being set to $null.

You need to create a variable $used before calling New-Object. Also, you're doing far too much formatting in calculating the used percentage - save the formatting until the very end. Below, I've made both changes

$used = "{0:P1}" -f (($disk.size - $disk.FreeSpace) / $disk.size);
$output = New-Object PSObject -Property @{
        deviceID     = $disk.caption
        FileSystem   = $disk.fileSystem
        FreeSpace    = $disk.freeSpace/1GB
        Size         = $disk.size/1GB
        VolumeName   = $disk.volumeName
        used = $used
        used2 = $used
        }