问题描述
我正在开发用于公司驱动器映射目的的 PowerShell 脚本。目前,该脚本正在获取登录的用户名并查询 AD 以存储其组。从那里,我们将他们的 AD 组与一个阵列(映射)进行比较,然后相应地映射他们的驱动器。
问题是,我们不想篡改它们当前的驱动器映射如果它们已经被正确映射(它们匹配映射数组字母/路径)。我试过进行比较、循环等,但似乎找不到一种好方法来比较当前映射的网络驱动器号/路径与数组,如果相同,则忽略它。
本质上,如果当前映射与阵列中的内容匹配,我们不希望断开网络驱动器的连接。
$mappings = @(
[pscustomobject]@{adgroup='ADGROUP1';driveletter='G';networkpath='\\server\location1'}
[pscustomobject]@{adgroup='ADGROUP2';driveletter='H';networkpath='\\server\location2'}
[pscustomobject]@{adgroup='ADGROUP3';driveletter='I';networkpath='\\server\location3'}
[pscustomobject]@{adgroup='ADGROUP4';driveletter='J';networkpath='\\server\location4'}
)
$groups = Get-ADPrincipalGroupMembership $env:username | select name
$currentDrives = Get-PSDrive -PSProvider FileSystem | Select-Object Name,displayRoot | Where-Object {$_.displayRoot -ne $null}
foreach ($mapping in $mappings) {
if ($groups -match $mapping.adgroup) {
Remove-PSDrive -Name $mapping.driveletter -Force -ErrorAction SilentlyContinue
New-PSDrive -Name $mapping.driveletter -PSProvider FileSystem -Root $mapping.networkpath -Persist -Scope Global -ErrorAction SilentlyContinue | Out-Null
}
}
解决方法
这令人困惑,因为 Get-PSDrive H
将显示 Root
属性是网络映射名称。但是 (Get-PSDrive H).Root
会返回 H:\
。很奇怪吧?
您可以使用 DisplayRoot 属性获取真实网络共享:
If((Get-PSDrive $mapping.driveletter).DisplayRoot -ne $mapping.networkpath){
#un-map and re-map the drive
}