我需要摆脱AD中不存在的一些用户,但仍然安装到应用程序中。
我有一个脚本,它提供用户列表并将它们分配给变量。目前我想要一个做notexist的用户列表。这适用于单个用户:
#One user in an Application
$Users = $location.Users.FindAll() | where {$_.username -like "*johnsmith*"} | select username
Username
--------
JohnSmith
#See if user exists in AD (Match Username with AD UserPrincipalName)
$users = $repository.Users.FindAll() |where {$_.username -like "*johnp*"} | select username
$users2 = Get-ADUser -Filter "UserPrincipalName -eq '$($users.username)'" -Properties LastLogonDate
if (!$users2 )
{
Write-Host "$users doesnt exist"
}
else
{
Write-Host "$users does exist"
}
> @{Username=JohnSmith} doesnt exist
我得到的问题是将这个提供给变量中多个用户的foreach循环。如何让它查看每个用户的对象并输出不存在的对象?
#List of all users in Appication
$Users = $location.Users.FindAll() | select username
Username
--------
JohnSmith
JohnSmith1
JohnSmith2
试过这个,但没有用,显示所有用户都存在,即使JohnSmith不存在如上:
$users = $location.Users.FindAll() |select username
$users2 = Get-ADUser -Filter "UserPrincipalName -eq '$($users.username)'"
foreach ($users2 in $users){
if (!$users2 )
{
write-host "$users2 doesnt exist"
}
else
{
write-host "$users2 does exist"
}
}
PS C:\>
@{Username=JohnSmith} does exist
@{Username=JohnSmith1} does exist
@{Username=JohnSmith2} does exist
答案 0 :(得分:-1)
未经测试,但这应该返回不在AD中的所有应用程序用户的列表:
$applicationUsers = $location.Users.FindAll() | select username
$adUsers = Get-ADUser -filter * | select -ExpandProperty UserPrincipalName
$users = $applicationUsers | Where username -NotIn $adUsers
你可以使用以下方法迭代它们:
$users | Foreach-Object { $_ }