Search code examples
powershelldiskspace

How to read disk drive space for each different path in a PowerShell script?


I have my first small project and I just started a PowerShell (total beginner).

We have three different shared C:\ drives and I need to output each disk storage info (e.g. total and free space) by using Powershell script.

Here is the script I made, but these three results are all the same even though they have different free spaces and total.

Can anyone please advise me on what is wrong with my ps script?

Plus, in the result, I don't want to display any other drives (e.g D and E) but only the C drive. How to do so?

[Script]

Set-Location -Path \\vm1\c$
Get-WmiObject -Class win32_logicaldisk | Format-Table DeviceId, @{n='Size'; e={[math]::Round($_.Size/1GB, 2)}}, @{n="FreeSpace"; e={[math]::Round($_.FreeSpace/1GB, 2)}}

Set-Location -Path \\vm2\c$
Get-WmiObject -Class win32_logicaldisk | Format-Table DeviceId, @{n='Size'; e={[math]::Round($_.Size/1GB, 2)}}, @{n="FreeSpace"; e={[math]::Round($_.FreeSpace/1GB, 2)}}

Set-Location -Path \\vm3\c$
Get-WmiObject -Class win32_logicaldisk | Format-Table DeviceId, @{n='Size'; e={[math]::Round($_.Size/1GB, 2)}}, @{n="FreeSpace"; e={[math]::Round($_.FreeSpace/1GB, 2)}}

[Result]

DeviceId   Size FreeSpace
--------   ---- ---------
C:       473.95    114.22
D:            0         0
E:            0         0



DeviceId   Size FreeSpace
--------   ---- ---------
C:       473.95    114.22
D:            0         0
E:            0         0



DeviceId   Size FreeSpace
--------   ---- ---------
C:       473.95    114.22
D:            0         0
E:            0         0


Solution

  • Setting location to an UNC Path does not mean you're actually querying the win32_logicaldisk of that remote host, you need to use the -ComputerName Parameter to query the remote hosts information. Also worth noting, you should start using Get-CimInstance instead of Get-WmiObject (no longer available in newer versions of PowerShell).

    As for displaying only the C drive, for this you can use -Filter. I've also added PSComputerName to your Format-Table returned properties so you can know which host the output belongs to.

    $vms = 'vm1', 'vm2', 'vm3'
    Get-CimInstance -Class win32_logicaldisk -Filter "DeviceID='C:'" -ComputerName $vms |
        Format-Table @(
            'PSComputerName'
            'DeviceId'
            @{ N='Size'; E={ [math]::Round($_.Size/1GB, 2) }}
            @{ N='FreeSpace'; E={ [math]::Round($_.FreeSpace/1GB, 2) }}
        )