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
CodePudding user response:
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) }}
)
CodePudding user response:
Set-Location
-Path \vm1\c$ does not work this way. it sets the default location on the filesystem for the current powershell session but does not influence get-wmiobject. to query remote computer you must use the parameter -computername
.
you should use the cim cmdlets as they replace the wmi-object cmdlet. the parameter -computername
supports an array as input so you only need to call get-wmiobject/get-ciminstance one time and if you only want to know about the C:\ drive, you can query for it:
$computers = @('vmName1','vmName2','nmName3')
Get-CimInstance -ComputerName $computers -Query "select freeSpace from win32_loogicaldoisk where deviceId='C:'" | select-object pscomputername,deviceid,freeSpace