PowerShell is a powerful scripting language and can do many things. One task that can be used over and over is to get the logical drives off a system. One you have this information you can then perform tasks like searching for files, directories, reporting usage etc..
In this post I will be simply showing how to create a variable and retrieve the data for the logical drives using WMI object win32_logicaldisk.
If we just enter Get-WmiObject win32_logicaldisk we see the output showing Device ID, DriveType, ProviderName, FreeSpace, Size and VolumeName.
PS C:\Windows\system32> Get-WmiObject win32_logicaldisk DeviceID : B: DriveType : 3 ProviderName : FreeSpace : Size : VolumeName : DeviceID : C: DriveType : 3 ProviderName : FreeSpace : 59039604736 Size : 159724335104 VolumeName : Windows 7 DeviceID : D: DriveType : 5 ProviderName : FreeSpace : Size : VolumeName : DeviceID : E: DriveType : 5 ProviderName : FreeSpace : Size : VolumeName :
Now let’s take this a bit further and tell it we want DriveType 3. Which in this instance we see drive D: removed from the list, which is DriveType 5 (CD-ROM)
PS C:\Windows\system32> Get-WmiObject win32_logicaldisk| ?{$_.drivetype -eq 3}
DeviceID : B:
DriveType : 3
ProviderName :
FreeSpace :
Size :
VolumeName :
DeviceID : C:
DriveType : 3
ProviderName :
FreeSpace : 59039604736
Size : 159724335104
VolumeName : Windows 7
So what can we do next? Well, how about let’s create a list of just the drive name? No problem, let’s build on the command and add the foreach-object and grab the name.
PS C:\Windows\system32> Get-WmiObject win32_logicaldisk| ?{$_.drivetype -eq 3} | foreach-object {$_.name}
B:
C:
Now we have something we can work with and can assign this to a variable that we can use in a script. Let’s take the line and add $drives = to the front of the command and create the $drives variable which we can reference.
$drives = Get-WmiObject win32_logicaldisk| ?{$_.drivetype -eq 3} | foreach-object {$_.name}
Now lets go a step further and get the first level of the directory for the drive. We need to do a foreach and use the Get-ChildItem cmdlet.
$drives = Get-WmiObject win32_logicaldisk| ?{$_.drivetype -eq 3} | foreach-object {$_.name}
foreach ($drivename in $drives)
{
cd -Path $drivename
Get-ChildItem $drivename
}
So as you can see there are many other possibilities from what was touched on here. Have fun and keep PowerShelling !!!
