I have a need to get rid of some users that do not exist in AD anymore but are still installed to an application, I have a script which provides a list of users and assigns them to a variable. At the moment I want a list of users that do notexist. This works for a single user:
#One user in an Application
$Users = $repository.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
Problem I am getting is feeding this to a foreach loop for multiple users in the variable. How can I put this to look through the object for each user and output the ones which do not exist?
#List of all users in Appication
$Users = $repository.Users.FindAll() | select username
Username
--------
JohnSmith
JohnSmith1
JohnSmith2
Tried this, but doesnt work, shows all users exist even though JohnSmith doesnt exist as above:
$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
Aucun commentaire:
Enregistrer un commentaire