powershell - Check shared drive is already mapped
问题描述
I'm using PowerShell for the first time to check if a unc path is already mapped, and if it is delete it to create it again under specific credentials.
The problem I have found is if the path exists in the net use list but has a drive letter, you have to delete it by the drive letter which can be of course random. So I need to find out the drive letter when I match it but I am clueless as to how.
$userPass = '/user:Domain\User password';
$ltr = ls function:[d-z]: -n | ?{ !(test-path $_) } | random;
$share = '\\\\server\\folder';
$newMap = 'net use '+ $ltr + ' '$share + ' '$userPass;
foreach ($con in net use) {
if ($con -match $share) {
$MappedLetter = /*something here to find the matched drive?*/
if ($MappedLetter) {
net use $MappedLetter /delete
} else {
net use $share /delete
}
}
};
net use $newMap;
[Edit]
I have tried the Get-PSDrive
but this only works IF the UNC path is mapped to a drive. As these can at times be a "zombie", i.e. exist in net use
but have no letter, this method won't always work. I can combine the two methods (above an Get-PSDrive
) but if anyone has a cleaner way please let me know!
解决方案
您应该能够通过以下方式检查特定共享是否已映射Get-PSDrive
:
$share = '\\server\share'
$drive = Get-PSDrive |
Where-Object { $_.DisplayRoot -eq $share } |
Select-Object -Expand Name
if ($drive) {
"${share} is already mapped to ${drive}."
}
如果您只想删除驱动器以防它被映射,您可以执行以下操作:
Get-PSDrive | Where-Object {
$_.DisplayRoot -eq $share
} | Remove-PSDrive
更新:
AFAIK PowerShell 无法直接枚举和删除断开连接的驱动器。您可以从注册表中获取该信息:
$share = '\\server\share'
$drive = Get-ItemProperty 'HKCU:Network\*' |
Where-Object { $_.RemotePath -eq $share } |
Select-Object -Expand PSChildName
或从输出中解析出来net use
:
net use | Where-Object {
$_ -match '(?<=^Unavailable\s+)\w:'
} | ForEach-Object {
$matches[0]
}
net use
但是,据我所知,只要驱动器保持断开连接,您仍然无法移除驱动器(例如 via )。要删除断开连接的驱动器(例如,当共享永久不可用时),您需要从注册表中删除映射信息:
$share = '\\server\share'
Get-ItemProperty 'HKCU:Network\*' |
Where-Object { $_.RemotePath -eq $share } |
Remove-Item
# also remove mount point in Windows Explorer
$key = 'Software\Microsoft\Windows\CurrentVersion\Explorer\MountPoints2'
$subkey = Join-Path $key ($share -replace '\\', '#')
Get-ItemProperty "HKCU:${subkey}" | Remove-Item
推荐阅读
- javascript - 更改outerHTML后传递一个元素
- database - Ms Access 表单 -> 表同步
- jquery - jQuery点击事件不起作用 - 表单提交后
- ldap - Kerberos 给了我什么 LDAP 没有?
- c# - Windows 7 访问冲突
- c# - 将 NuGet 包添加到非 VS .cs 文件
- linux - 在 Linux 中从文本文件中删除 html 标签
- php - PHP mailer + angular4 - 404 找不到问题
- c# - 查询显示所需信息的一半 LINQtoXML C#
- typescript - tslint 错误:期望赋值或函数调用