获取映射的网络驱动器标签

问题描述

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

获得多个属性
Get-Object Win32_MappedLogicalDisk 

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

解决方法

您可以为此使用 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
,

我不知道可以为您提供该信息的 cmdlet。我相信您可以通过使用 gci 查看注册表来找到它,但是您需要清理输出。

get-childitem "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2"

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...