Hi guys,
Another one that’s caught me out - fairly simple goal - I have a list of usernames, that I would like to verify through powershell, whether the account exists.
I’m not able to get it to work as intended though. The script runs without error but is obviously not reporting the right data. Not sure why, as I’ve used if statements many many times before, and never had such a problem. Maybe I’m missing some syntax or operators.
Here’s my code:
$Users = import-csv "homedrives-jan15.csv"
$OutFile = "homedrive-audit.csv"
$Header = "username,account status"
Add-Content -Path $OutFile -Value $Header
foreach [$User in $Users]
{
$GetUser = Get-AdUser -Filter {sAMAccountName -eq '$[$User.Username]'}
if [$GetUser -eq $null]
{
$Status = "User Not Found"
Write-Host "$[$User.Username] account not found"
}
Else
{
$Status = "User Exists"
Write-Host "$[$User.Username] exists"
}
$OutData = $User.Username + "," + $Status
Add-Content -Path $OutFile -Value $OutData
}
My issue is that both the terminal output AND the CSV output are all showing account not found for everything, which I know is obviously wrong. No matter what logic I use to verify the account, the script will only ever use the first if statement output, and completely ignore the Else statement.
Anyone spot what I’m doing wrong here?
Thanks!