簡體   English   中英

獲取映射的網絡驅動器標簽

[英]Get mapped network drives labels

有沒有辦法獲取映射的網絡驅動器標簽? 我知道可以通過

Get-Object Win32_MappedLogicalDisk 

但是它們都不是標簽(請不要誤解,我不想要名稱,即 K:,我想要標簽,即我的網絡驅動器)

您可以為此使用 Com Shell.Application object:

$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 

對上面的一些解釋:

使用 COM object 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

另一種方法是將 go 放入注冊表,但請記住,映射的網絡文件夾取消映射后,舊的注冊表值仍然存在。 這就是為什么下面的代碼仍然首先使用兩種方法之一來查找活動網絡映射的原因:

# 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 也在這里:

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

我不知道會為您提供該信息的 cmdlet。 我相信您可以通過使用 gci 查看注冊表來找到它,但您需要清理 output。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM