FIXED: I did have to change if ($null -eq $FoundUser) and then if essentiall NULL -eq NULL, that user doesn't exist... SORRY
I would really love some help as I've on/off been struggling with this logic with Get-ADUser for user creation.
I'm using Powershell 7.0 - 7.2.1 (latter currently) and having this problem with VSCode and running it in "console". We have a 2008 R2 forest but 2016 and 2019 DCs. Essentially "Get-ADUser -Filter" doesn't return any value. I'm trying to use an if statement for if $null -ne $SamAccountName.
Any thoughts? I thought I found the answer here but no luck for me.
$Users = Import-Csv -delimiter "`t" -Path "C:\Users\michel_m\Documents\Scripts\PowerShell\Staff\StaffData.txt"
#$sam = ""
#Generate data to use in creating user below
foreach ($User in $Users) {
$SAMAccount = $User.Username
$Filter = "sAmAccountname -eq '$SamAccount'
$FoundUser = Get-ADUser -Filter $Filter
Write-Host "HERE IS" $FoundUser
$results = $FoundUser.SamAccountName
#if ($null -ne $FoundUser)
if ($null -ne $results)
{
Write-Host $results "Are the results"
Write-Host $User "is the user"
Write-Host $SAMAccount "Is the SAM user"
Write-Host $FoundUser "Is the found user"
#NewUser_Function
($Dates + " - " + $user.username + " has been created") | out-file -filepath $OutputFile1 -append
#Write-Host "Pause 15 seconds"
Start-Sleep 15
Write-Host $user.username + " Has been created"
$Body = $user.username + " Has been created"
#schtasks.exe /run /s "OHDC01" /tn "GADS Sync - Users"
}
else
{
Write-Host $Filter
Write-Host $results "Are the results"
Write-Host $User "is the user"
Write-Host $SAMAccount "Is the SAM user"
Write-Host $FoundUser "Is the found user"
Write-Host $null is null
write-host $user.username + " already exists"
($Dates + " - " + $user.username + " already exists") | out-file -filepath $OutputFile2 -append
$Body = $user.username + " already exists",
"\\OHDC01\C$\Scripts\StaffCreation\NewStaff\",
"\\OHDC01\C$\Scripts\StaffCreation\NewStaff\"
}
}
Output
HERE IS
sAmAccountname -like 'mangold_m' | Select-object SamAccountName
Are the results
@{FirstName=Michelle; LastName=Mangold; BuildingName=OAK; Position=Aide; Username=mangold_m; Email=mangold_m@Wonderfullife.org} is the user
mangold_m Is the SAM user
Is the found user
is null
mangold_m + already exists
HERE IS
sAmAccountname -like 'metzner_m' | Select-object SamAccountName
Are the results
@{FirstName=Melissa; LastName=Metzner; BuildingName=OHHS; Position=Aide; Username=metzner_m; Email=metzner_m@Wonderfullife.org} is the user
metzner_m Is the SAM user
Is the found user
is null
metzner_m + already exists