Listing Network Drives

by Jan 3, 2019

There are many ways to create a list of network drives. One involves a COM interface that was used by VBScript as well, and we’ll pick it to illustrate a special PowerShell technique.

To dump all network drives, simply run these lines:

$obj = New-Object -ComObject WScript.Network
$obj.EnumNetworkDrives()

The result may look similar to this:

 
PS> $obj.EnumNetworkDrives() 

X:
\\storage4\data
Z:
\\127.0.0.1\c$
 

The method returns two strings per each network drive: the assigned drive letter, and the original URL. To turn this into something useful, you would have to create a loop that returns two elements per iteration.

Here is a clever approach that does just this:

$obj = New-Object -ComObject WScript.Network
$result = $obj.EnumNetworkDrives() 

Foreach ($entry in $result)
{
    $letter = $entry
    $null = $foreach.MoveNext()
    $path = $foreach.Current
  
  
    [PSCustomObject]@{
        DriveLetter = $letter
        UNCPath = $path
    }
} 

Inside the foreach loop, there is a little-known automatic variable called $foreach. It controls the iterations. When you call MoveNext(), it iterates over the collection, moving to the next element. With Current, you can read the current value of the iterator.

This way, the loop processes two items at a time instead of just one. The two items are then combined in a custom object. The result looks like this:

 
DriveLetter UNCPath       
----------- -------       
X:          \\storage4\data
Z:          \\127.0.0.1\c$
 

psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU – with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!

Twitter This Tip! ReTweet this Tip!