title: PowerShell turning an if else statement to a Foreach Loop
body: <p>I have a need to get rid of some users that do not exist in AD anymore but are still installed to an application. </p>
  
  <p>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:</p>
  
  <pre><code>#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"
  }
  
  
  &gt; @{Username=JohnSmith} doesnt exist
  </code></pre>
  
  <p>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?</p>
  
  <pre><code>#List of all users in Appication
  
  $Users = $location.Users.FindAll() | select username 
  
  Username                                                                                                                                                                        
  --------                                                                                                                                                                        
  
  JohnSmith
  JohnSmith1
  JohnSmith2
  </code></pre>
  
  <p>Tried this, but doesnt work, shows all users exist even though JohnSmith doesnt exist as above:</p>
  
  <pre><code>$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:\&gt;
  @{Username=JohnSmith} does exist
  @{Username=JohnSmith1} does exist
  @{Username=JohnSmith2} does exist
  </code></pre>