Search code examples
powershellnetwork-programminglabeldrivemapped-drive

Get mapped network drives labels


Is there a way to get mapped network drives labels? I know it's possible to get multiple properties through the

Get-Object Win32_MappedLogicalDisk 

But none of them are labels (please do not misunderstand, I do not want Name i.e. K:, I want labels i.e. My Network drive)


Solution

  • You could use the Com Shell.Application object for this:

    $shell  = New-Object -ComObject Shell.Application
    (Get-WmiObject -Class Win32_MappedLogicalDisk).DeviceID | 
    # or (Get-CimInstance -ClassName Win32_MappedLogicalDisk).DeviceID | 
    # or ([System.IO.DriveInfo]::GetDrives() | Where-Object { $_.DriveType -eq 'Network' }).Name |
    Select-Object @{Name = 'Drive'; Expression = {$_}},
                  @{Name = 'Label'; Expression = {$shell.NameSpace("$_").Self.Name.Split("(")[0].Trim()}}
    
    # when done, clear the com object from memory
    $null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($shell)
    [System.GC]::Collect()
    [System.GC]::WaitForPendingFinalizers()
    

    Output:

    Drive Label     
    ----- -----     
    X:    MyCode 
    

    Some explanation for the above:

    Using the COM object Shell.Application, you can drill down through its properties and methods.

    .NameSpace  create and return a Folder object for the specified folder
    .Self       gets a Read-Only duplicate System.Shell.Folder object
    .Name       from that we take the Name property like 'MyCode (X:)'
    .Split      this name we split on the opening bracket '(',
    [0]         take the first part of the splitted name and 
    .Trim()     get rid of any extraneous whitespace characters
    

    Another way is to go into the registry, but remember that after a mapped network folder is unmapped, the old registry value remains. This is why below code still uses one of two methods to find active network mappings first:

    # the registry key to search in
    $regKey = 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2'
    
    # list the mapped network drives and loop through
    # you can also use Get-CimInstance -ClassName Win32_MappedLogicalDisk
    Get-WmiObject -Class Win32_MappedLogicalDisk | ForEach-Object {
        # create the full registry key by replacing the backslashes in the network path with hash-symbols
        $key = Join-Path -Path $regKey -ChildPath ($_.ProviderName -replace '\\', '#')
        # return an object with the drive name (like 'X:') and the Label the user gave it
        [PsCustomObject]@{
            Drive = $_.DeviceID  
            Label = Get-ItemPropertyValue -Path $key -Name '_LabelFromReg' -ErrorAction SilentlyContinue
        }
    }
    

    Output here also:

    Drive Label 
    ----- ----- 
    X:    MyCode