是否可以通过EmployeeID而不是UPN阻止Office365中的用户帐户?
这是我尝试过的脚本,但只能被UPN阻止:
Import-Csv 'C:\BlockedUsers.csv' | ForEach-Object {
$upn = $_."UserPrincipalName"
Set-MsolUser -UserPrincipalName $upn -BlockCredential $true
}
答案 0 :(得分:0)
如果您的csv文件包含名为EmployeeId
的列,则可以使用Get-AdUser
cmdlet使用该列获取UserPrincipalName属性:
Import-Csv 'C:\BlockedUsers.csv' | ForEach-Object {
$user = Get-ADUser -Properties EmployeeID -Filter "EmployeeID -eq $($_.EmployeeID)"
if ($user) {
$upn = $user.UserPrincipleName
Set-MsolUser -UserPrincipalName $upn -BlockCredential $true
}
}
修改
从您的评论来看,EmployeeID
属性在您的组织中似乎并不总是唯一的。
在这种情况下,下面的代码应该可以处理
Import-Csv 'C:\BlockedUsers.csv' | ForEach-Object {
$user = Get-ADUser -Properties EmployeeID -Filter "EmployeeID -eq $($_.EmployeeID)"
if ($user) {
foreach ($usr in $user) {
Write-Host "Blocking user $($usr.Name)"
$upn = $usr.UserPrincipleName
Set-MsolUser -UserPrincipalName $upn -BlockCredential $true
}
}
else {
Write-Host "User with EmployeeID $($_.EmployeeID) not found"
}
}
P.S。如果您的CSV可以包含EmployeeID
列的空值,请将第一行更改为
Import-Csv 'C:\BlockedUsers.csv' | Where-Object {$_.EmployeeID -match '\S'} | ForEach-Object {
摆脱空值或仅包含空格的值。
如果您确定CSV包含列EmployeeId
,并且您没有误认为AD属性为EmployeeNumber
,那么这也许对您有用。
它使用Get-ADUser
来获取用户对象的集合,这些对象实际上在其EmployeeId属性中具有,并通过与您使用Where-Object
从CSV中读取的对象进行比较来对其进行优化。
EmployeeId
和EmployeeNUmber
均为类型String
的AD属性。您可以查找here
# first read the CSV into an array containing only the values from the 'EmployeeID' column
$blockedUserIds = Import-Csv 'C:\BlockedUsers.csv' | Select-Object -ExpandProperty EmployeeId -Unique
# next get an array of user objects that have something in the EmployeeID attribute and only
# leave the users where the attribute can be matched to a value captured in the CSV array above
# use the '@(..)' syntax to force the result to be an array, even if only one item is found
$usersToBlock = @(Get-ADUser -Properties EmployeeID, Name, UserPrincipalName -Filter "EmployeeID -like '*'" |
Where-Object { $blockedUserIds -contains $_.EmployeeID })
# you can also use the '-LDAPFilter' parameter
# $usersToBlock = @(Get-ADUser -Properties EmployeeID, Name, UserPrincipalName -LDAPFilter "(employeeID=*)" |
# Where-Object { $blockedUserIds -contains $_.EmployeeID })
# you now should have an array of user objects that need to be blocked
if ($usersToBlock.Count) {
Write-Host "Blocking $($usersToBlock.Count) users.." -ForegroundColor Green
$usersToBlock | ForEach-Object {
Write-Host "Blocking user $($_.Name)"
Set-MsolUser -UserPrincipalName $($_.UserPrincipleName) -BlockCredential $true
}
}
else {
Write-Warning "No users found with an EmployeeId property that matches any of the values in BlockedUsers.csv"
}