Remove Name Notepad file if doesnt exist in AD through powershell

$Users = GC "Desktop\Master.txt"

foreach ($user in $users) {

$userobj = $(try {Get-ADUser $user} catch {$Null})

If ($userobj -ne $Null) {

   Write-Host "$User Exists"

} else {

   Write-Host "$User Doesn't Exist"


I am using this code to check if a user exists in AD. Later on this notepad file is processed to delete the users that are on the file. I was going to see if it was possible that I can remove the users off the list that don’t exist. Is there a command to remove the line from the Notepad file that has the names on if the user doesn’t exist in AD

>Solution :

Write a function to test just a single user:

function Test-ADUser {

  try {
    $null = Get-ADUser @PSBoundParameters -ErrorAction Stop

    # user must exist if we reached this point
    return $true
  catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]{
    return $false

Now you can use Where-Object to filter the list from the text file based on what the function determines:

# Read list from file, filter out usernames that don't exist
$filteredList = Get-Content "Desktop\Master.txt" |Where-Object { Test-ADUser -Identity $_ }

# Write filtered data back to disk
$filteredList |Set-Content "Desktop\Master.txt" -Force

Leave a Reply