Forum Discussion
Powershell Get-ADuser if Statement
- Mar 25, 2022
A small update here.
$users=Import-Csv C:\Users\f.malaeb\Downloads\user1.csv foreach ($user in $users){ #Here Checking if the user is exist if ((Get-ADUser -Filter "SamAccountName -eq '$($user.Username)'")){ write-host $($user).username "is exist, Lets check the email" -ForegroundColor Green #If the user exist Check if the Email is exist if (Get-Mailbox $user.Username -ErrorAction SilentlyContinue){ #Here will create a mailbox for this user as its exist in AD but not in Exchange Write-Host $User.Username "Already have an email" -ForegroundColor Green } Else{ Write-Host "Creating a New mailbox for" $User.Username -ForegroundColor Yellow} } Else{ Write-Host $($User).Username "is NOT exists" -ForegroundColor Red} }The script will:
- Check if the user exists or not
- If a user exists, then and as you already got an active exchange session, use it to check if the user have a mailbox.
- if dont , then create a mailbox
-if the user is not exist then create the user.
Please Give a try to this code and let me know if things are working as expected.
You should get a single user and action based on the single users.
$users=Import-Csv C:\Users.csv
foreach ($user in $users){
if ((Get-ADUser -Filter "SamAccountName -eq '$($user.Username)'")){
write-host $($user).username "is exist, Creating Email for this user" -ForegroundColor Green
}
Else{
Write-Host $($User).Username "is NOT exists" -ForegroundColor Red}
}
Sweet, thank you.
But sometimes users will already exist but don't have email so we need validate that the user does or doesn't have email address that why I was looking use the attribute mail.
$users=Import-Csv C:\Users.csv
foreach ($user in $users){
if ((Get-ADUser -Filter "mail -eq '$($user.Username)@email.adress'")){
write-host $($user).username "is exist, Creating Email for this user" -ForegroundColor Green
}
Else
{
Write-Host $($User).Username "is NOT exists" -ForegroundColor Red
}
- farismalaebMar 25, 2022Iron Contributor
A small update here.
$users=Import-Csv C:\Users\f.malaeb\Downloads\user1.csv foreach ($user in $users){ #Here Checking if the user is exist if ((Get-ADUser -Filter "SamAccountName -eq '$($user.Username)'")){ write-host $($user).username "is exist, Lets check the email" -ForegroundColor Green #If the user exist Check if the Email is exist if (Get-Mailbox $user.Username -ErrorAction SilentlyContinue){ #Here will create a mailbox for this user as its exist in AD but not in Exchange Write-Host $User.Username "Already have an email" -ForegroundColor Green } Else{ Write-Host "Creating a New mailbox for" $User.Username -ForegroundColor Yellow} } Else{ Write-Host $($User).Username "is NOT exists" -ForegroundColor Red} }The script will:
- Check if the user exists or not
- If a user exists, then and as you already got an active exchange session, use it to check if the user have a mailbox.
- if dont , then create a mailbox
-if the user is not exist then create the user.