首页 > 解决方案 > 获取映射的网络驱动器标签

问题描述

有没有办法获取映射的网络驱动器标签?我知道可以通过

Get-Object Win32_MappedLogicalDisk 

但是它们都不是标签(请不要误解,我不想要名称,即 K:,我想要标签,即我的网络驱动器)

标签: powershellnetworkinglabeldrivemapped-drive

解决方案


您可以为此使用 Com Shell.Application 对象:

$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()

输出:

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

对上面的一些解释:

使用 COM 对象 Shell.Application,您可以深入了解它的属性和方法。

.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

另一种方法是进入注册表,但请记住,在映射的网络文件夹被取消映射后,旧的注册表值仍然存在。这就是为什么下面的代码仍然首先使用两种方法之一来查找活动网络映射的原因:

# 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
    }
}

这里也有输出:

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

推荐阅读