Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Write a function to test just a single user:

function Test-ADUser {
  param($Identity)

  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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading