do
{
$username = Read-Host -Prompt "Enter First Name"
$Name = $username
$User = Get-ADUser -LDAPFilter "(sAMAccountName=$Name)"
if ($username -eq "done")
{
Write-Host -ForegroundColor Red "Done, Thank You"
}
If ($User -eq $null) {"User does not exist in AD"}
Else {"User found in AD"}
}
while ($username -ne "done")
The script is working i want that when i type “done” the script will end
in this stage the script ends when i type done but its givin me mesage:User does not exist in AD
any help how i can stop the script without tihs message?
If you think about the logic here, you’re trying to get the user from AD even when the user inputs ‘done’.
If you want to use the do/while structure, you’ll need to change your if statements:
do {
$username = Read-Host -Prompt "Enter First Name"
$Name = $username
if ($username -ne "done") {
$User = Get-ADUser -LDAPFilter "(sAMAccountName=$Name)"
if ($null -eq $user) { "User does not exist in AD" }
else { "User found in AD" }
}
else {
Write-Host -ForegroundColor Red "Done, Thank You"
}
}
while ($username -ne "done")
Is there a reason why you’re assigning the input to $Name rather than just using $username in your filter?
Note: $null should go on the left when using a comparison operator.
Thank you as always @Olaf you are the best
I used you script to change the done button to empty string thank you
do {
$username = Read-Host -Prompt 'Enter Logon Name'
If ([string]::IsNullOrEmpty($username)) {
Break
}
ElseIf ($username -ne $null) {
if (Get-ADUser -LDAPFilter "(sAMAccountName=$username)") {
'User found in AD'
}
else {
'User does not exist in AD'
}
}
}
while ($username -ne $null)
Write-Host -ForegroundColor Red 'Done, Thank You'
If I got it right you can shorten your code slightly to this:
do {
$username = Read-Host -Prompt 'Enter Logon Name'
If (-not ([string]::IsNullOrEmpty($username))) {
if (Get-ADUser -LDAPFilter "(sAMAccountName=$username)") {
'User found in AD'
}
else {
'User does not exist in AD'
}
}
}
while (-not ([string]::IsNullOrEmpty($username)))
Write-Host -ForegroundColor Red 'Done, Thank You'
@matt-bloomfield already pointed out to place $null on the left hand side when you use it in comparisons because it can cause unexpected behaviour when you don’t. Here you can read more about $null: