title: Powershell to output results to CSV of AD query for a particular OU
body: <p>I have a list of users and and I need to query whether or not they are in a particular OU or not.  I have a Powershell that gives me the nearly the exact results I want in the console, but I would like it written to CSV file instead.  Could someone please help me with the syntax.</p>
  
  <pre><code>$Usernames = Get-Content -path .\Usernames.txt
  
  # Running against user list
  ForEach ($Username in $Usernames)
  {
  $ADuser = Get-ADUser -identity $Username –properties *
  $UserOU = $ADuser.CanonicalName.ToString().Split('/')[2]
  
          if ($userOU -match "OUName_A") {
              $OU = "FriendlyOUName_A"
              write-host $Username $OU -foregroundcolor green
          }
          elseif ($userOU -match "OUName_B") {
              $OU = "FriendlyOUName_B"
              write-host $Username $OU
          }
          else {
              write-host $Username "Disabled" -foregroundcolor red
          }
  }
  </code></pre>
  
  <p>So the screen output now looks like:</p>
  
  <pre><code>username#1 FriendlyOUName_A
  username#2 FriendlyOUName_B
  username#3 disabled
  Get-ADUser : Cannot find an object with identity: 'username#4' under: 'DC=subdomain,DC=company,DC=com'.
  At C:\temp\FindOUofUsers.ps1:8 char:11
  + $ADuser = Get-ADUser -identity $Username –properties *
  +           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : ObjectNotFound: (username#4:username#4) [Get-ADUser], ADIdentityNotFoundException
      + FullyQualifiedErrorId : Cannot find an object with identity: 'username#4' under: 'DC=subdomain,DC=company,DC=com'.,Microsoft.ActiveDirectory.Management.Commands.GetADUser
  </code></pre>
  
  <p>It would be helpful to capture the error state as <code>username#4 Deleted</code></p>