powershell - 获取映射的网络驱动器标签
问题描述
有没有办法获取映射的网络驱动器标签?我知道可以通过
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
推荐阅读
- python - 如何在 PyTorch 的 2D 矩阵输入中编码位置信息
- .net - .NET 如何同时处理 json 对象的 API 流
- javascript - 如何将在 Clever Cloud 上运行的 Rust 服务与自定义域绑定?
- excel - 根据另一个列值验证列日期格式
- php - HTML 表单动作属性登陆另一个文件夹中的文件。提交错误 404 文件未找到
- for-loop - 我不知道我的 for 循环有什么问题,但它不起作用。任何帮助都会很棒
- javascript - AWS DynamoDB 模拟始终匹配
- node.js - 模块构建失败:错误:检测到重复的插件/预设
- python - 是否可以为每个行为特征指定一个特定的“后特征”挂钩?
- java - 无需在每个阶段重新编译即可运行 GitlabCI 目标