Ricky Ricky - 5 months ago 51
PowerShell Question

Powershell - Exclude P: Drive from foreach loop

I have a script that goes through a text file of servers and reports on free disk space under 25% and 10%. However some servers have a P: drive which is used for a paging file, and therefore I wish the loop to ignore this drive.

Here is the loop part:

# Start processing disk space reports against a list of servers
foreach($computer in $computers)
$disks = Get-WmiObject -ComputerName $computer -Class Win32_LogicalDisk -Filter "DriveType = 3" -EA SilentlyContinue
$computer = $computer.toupper()
foreach($disk in $disks)
$deviceID = $disk.DeviceID;
$volName = $disk.VolumeName;
[float]$size = $disk.Size;
[float]$freespace = $disk.FreeSpace;
$percentFree = [Math]::Round(($freespace / $size) * 100, 2);
$sizeGB = [Math]::Round($size / 1073741824, 2);
$freeSpaceGB = [Math]::Round($freespace / 1073741824, 2);
$usedSpaceGB = $sizeGB - $freeSpaceGB;
$color = $whiteColor;

I'm at a very basic level with powershell, so any help with the syntax and how to exclude the P: drive would be appreciated


Add a condition to the WMI filter to exclude volumes with DeviceID = P::

$disks = Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType = 3 AND DeviceID != 'P:'" -ComputerName $computer -EA SilentlyContinue

Alternatively, filter the $disks collection with Where-Object:

foreach($disk in $disks |Where-Object {$_.DeviceID -ne 'P:'}) 
    # ...