SOLVED

Powershell Get-ADuser if Statement

Occasional Contributor
Good afternoon all
Can I please have help with the following:

Problem 1:
In the image attached I am trying to get AD user attribute "mail" and see if it equal company's email address but for some reason it returns everyone has email but which isn't correct.
If user mail attribute is null then it will create the mailbox but if it they do they pass.

Problem 2:
Trying to see if their is way to do remote session to skype for business management shell on primes. As I know how to connect to remote exhcnage management shell.
7 Replies

@Hjb118 

Hi

For ease of use, next time write the code as Code Format in this community so we can copy and paste and do a basic test.

Anyway. So if you try to debug the file, what is the value of $User for example, add the following line after the Foreach

write-host $($Username), are you getting a single user, or are you getting a full list of users

I tried your code and it seems to be fine. can you please share the CSV structure and share some of the output.

For S4B use the following command

$PS=New-PSSession -ComputerName aud-lnc-n1
Invoke-Command -Session $ps -ScriptBlock {Import-Module Skypeforbusiness}
Import-PSSession $ps

or an easier way is to install S4B management shell.

 

 

@farismalaeb 

 

Apologies I have now added all my code for you to see.

 

The code snippet below is to test see if user mail attribute has their address if not create the mail box but for some reason when I test it for multiple use, it return all users have mailbox which incorrect.

foreach ($user in $aduser){
if (Get-ADUser -Filter "mail -eq ""$($Username)@email.address""")
{
write-host "$Username"
write-host "do nothing"
}
else
{
write-host "$Username" write-host "create mailbox" } }

 

The code snippet below is to test see if user mail attribute has their address if not create the mail box but for some reason when I test it for multiple use, it return all users have mailbox which incorrect.


foreach ($user in $aduser){ if (Get-ADUser -Filter "proxyAddresses -like ""*$($User)@email.address*""") { write-host "$Username" write-host "do nothing" } else { write-host "$Username" write-host "create Skype account" } }


The code below is my script with some details taken out. 

# Fucntion is to create a password String
function Get-RandomCharacters($length, $characters) {
    $random = 1..$length | ForEach-Object { Get-Random -Maximum $characters.length }
    $private:ofs=""
    return [String]$characters[$random]
}

# Takes input and scambles the string
function Scramble-String([string]$inputString){     
    $characterArray = $inputString.ToCharArray()   
    $scrambledStringArray = $characterArray | Get-Random -Count $characterArray.Length     
    $outputString = -join $scrambledStringArray
    return $outputString 
}

#Imports T2_user.csv file and stores it in the variable $ADUsers
$ADUsers = Import-csv C:\temp\"T2_User_test.csv"

Write-host "Active directory section" -ForegroundColor Green -BackgroundColor Black
write-host ""


<# Foreach Loop Runs for each row containing user details in the CSV file.
The Foreach will do the following:
1.Vaildidates user to see if users already been created
2.Creates User if not already been created
2.1.Writes to screen that the user has been created 
2.2. Sets users Nationality
2.3. Adds upto 10 Security Groups if any are in the CVS file.
#>
foreach ($User in $ADUsers){

    #Read user data from each field in each row and assign the data to a variable as below
    Write-Host "-------------------------------------------------------------------" 
    Write-Host "Imported details for $($user.username)"   -ForegroundColor Green                          # Writes to screen the user that about to be created
    $Username = $User.username                                                                            # Sets the Vairable 'username' to users Strategic username
    $Firstname = $User.firstname                                                                          # Sets the Vairable 'Firstname' to users firstname
    $Lastname = $User.lastname                                                                            # Sets the Vairable 'Lastname' to users lastname 
    $OU = $User.ou                                                                                        # Account will be created in the OU provided by the $OU variable read from the CSV file
    $Date = $user.date                                                                                    # This varible is used to set the expire date  E.G "2022-03-25 00:00:00"
    $subdomain = $user.subdomain
    $CEC = $user.CEC                                                                                                                                                                  
    $H_Drive_Address = "\\$($user.subdomain).diep.mil.au\$($user.CEC)\userdata\home\$($User.username)"    # This Varible is used to Set the Home Directory Address
    $Nationality = $user.nationality                                                                      # Set the Nationaility
    $Security_Group1 = $user.Security_Group1                                                              # Sets the vairable for a security group for user
    $Security_Group2 = $User.Security_Group2                                                              # Sets the vairable for a security group for user
    $Security_Group3 = $User.Security_Group3                                                              # Sets the vairable for a security group for user
    $Security_Group4 = $User.Security_Group4                                                              # Sets the vairable for a security group for user
    $Security_Group5 = $user.Security_Group5                                                              # Sets the vairable for a security group for user
    $Security_Group6 = $User.Security_Group6                                                              # Sets the vairable for a security group for user
    $Security_Group7 = $User.Security_Group7                                                              # Sets the vairable for a security group for user
    $Security_Group8 = $User.Security_Group8                                                              # Sets the vairable for a security group for user
    $Security_Group9 = $User.Security_Group9                                                              # Sets the vairable for a security group for user
    $Security_Group10 = $User.Security_Group10                                                            # Sets the vairable for a security group for user


                        
    # The 'Password' Vairable Calls the Get Get-RandomCharacters function to get random letters, numbers and sysmbols, then the 'password' will call the Scramble-String
    # Scamble the string of letters, numbers and sysmbols. This Vairable is to set random password for a T2 user before they restest their password.
    $password = Get-RandomCharacters -length 10 -characters 'abcdefghiklmnoprstuvwxyz'
    $password += Get-RandomCharacters -length 2 -characters 'ABCDEFGHKLMNOPRSTUVWXYZ'
    $password += Get-RandomCharacters -length 2 -characters '1234567890'
    $password += Get-RandomCharacters -length 2 -characters '!"§$%&/()=?}][{@#*+'
    $password = Scramble-String $password



    #Check to see if the user already exists in the AD

    if (Get-ADUser -Filter "samAccountName -eq ""$($Username)""")
    {
    #If the user does exist, give a warning
        Write-Warning "A user account with username $Username already exists in Active Directory."
    }
    else
    {
    New-ADUser -Name "$($Username)" -GivenName $Firstname  -Surname $Lastname  -DisplayName "$Lastname, $Firstname"  -UserPrincipalName "$($Username)@$($Subdomain)" -Path $OU -AccountPassword (convertto-securestring $Password -AsPlainText -Force) -HomeDrive "H:" -HomeDirectory $H_Drive_Address -AccountExpirationDate $Date -WhatIf

    #The following command will set AD user nationaility
    set-ADuser -Identity $($Username) -Replace @{Nationality="$Nationality"}  #Test this command
 
    # Writes to screen the user that has been created
    Write-host "Created Active dicrectory user for $($Username)" -ForegroundColor Green

    #The section below is to add user to security groups

    # This adds user to the security group set in vairable Security_Group1
    if ($Security_Group1 -ne @($null))
    {
        Add-ADGroupMember -Identity $Security_Group1 -Members $Username
        Write-host "Added $($Username) to"$($Security_Group1)"Security Group"
    }

    # This adds user to the security group set in vairable Security_Group2
    if ($Security_Group2 -ne @($null))
    {
        Add-ADGroupMember -Identity $Security_Group2 -Members $Username
        Write-host "Added $($Username) to"$($Security_Group2)"Security Group"
    }

    # This adds user to the security group set in vairable Security_Group3
    if ($Security_Group3 -ne @($null))
    {
        Add-ADGroupMember -Identity $Security_Group3 -Members $Username
        Write-host "Added $($Username) to"$($Security_Group3)"Security Group"
    }

    # This adds user to thet security group set in vairable Security_Group4
    if ($Security_Group4 -ne @($null))
    {
        Add-ADGroupMember -Identity $Security_Group4 -Members $Username
        Write-host "Added $($Username) to"$($Security_Group4)"Security Group"
    }

    # This adds user to the security group set in vairable Security_Group5
    if ($Security_Group5 -ne @($null))
    {
        Add-ADGroupMember -Identity $Security_Group5 -Members $Username
        Write-host "Added $($Username) to"$($Security_Group5)"Security Group"
    }

    # This adds user to the security group set in vairable Security_Group6
    if ($Security_Group6 -ne @($null))
    {
        Add-ADGroupMember -Identity $Security_Group6 -Members $Username
        Write-host "Added $($Username) to"$($Security_Group6)"Security_Group"
    }

    # This adds user to the security group set in vairable Security_Group7
    if ($Security_Group7 -ne @($null))
    {
        Add-ADGroupMember -Identity $Security_Group7 -Members $Username
        Write-host "Added $($Username) to"$($Security_Group7)"Security_Group"
    }

    # This adds user to the security group set in vairable Security_Group8
    if ($Security_Group8 -ne @($null))
    {
        Add-ADGroupMember -Identity $Security_Group8 -Members $Username
        Write-host "Added $($Username) to"$($Security_Group8)"Security_Group"
    }

    # This adds user to thet security group set in vairable Security_Group9
    if ($Security_Group9 -ne @($null))
    {
        Add-ADGroupMember -Identity $Security_Group9 -Members $Username
        Write-host "Added $($Username) to"$($Security_Group9)"Security_Group"
    }

    # This adds user to the security group set in vairable Security_Group10
    if ($Security_Group10 -ne @($null))
    {
        Add-ADGroupMember -Identity $Security_Group10 -Members $Username
        Write-host "Added $($Username) to"$($Security_Group10)"Security_Group"
    }
    
}
}


#section for Exchange account enabling
#--------------------------
# This scprit will Import CSV file you created using the Export_User_CEC_Subdomain scirpt, then for each user in the CSV will Enable each mailbox.
write-host ""
#Exchange Import session Varibles
write-host "Get T1 Credentials" -ForegroundColor Green -BackgroundColor Black 
$userCredential = Get-Credential
write-host ""
write-host "Import Remote session " -ForegroundColor Green -BackgroundColor Black
$Exchange_Remote_Session = New-PSSession -ConfigurationName Microsoft.Exchange -verbose -ConnectionUri http://Server/powershell/ -Authentication Kerberos -Credential $userCredential
Import-PSsession $Exchange_Remote_Session # Imports Exchange management shell Remote session into Powershell
write-host ""
Write-host "Exchange Section" -ForegroundColor Green -BackgroundColor Black
write-host "--------------------------------------------------------------------------"


# For each user in the T2_user.csv file it will check to see if they already have mailbox write a message if they do and if not enable their mailbox.
foreach ($User in $ADUsers){

$Username = $User.username                                                                            # Sets the Vairable 'username' to users Strategic username  
$subdomain = $user.subdomain                                                                          
$CEC = $user.CEC                                

if (Get-ADUser -Filter "mail -eq ""$($Username)@email.address""")
{
write-warning "$Username already has a mailbox enabled"
}
else
{
 Enable-Mailbox -identity "$($subdomain)\$($Username)" -Database "MBDB01-$($CEC)" -PrimarySMTPAddress "$($Username)@email.address" -domaincontroller "server.name"
}
}

# Removes the  Exchange management shell Remote session from Powershell 
Remove-PSSession -Session $Exchange_Remote_Session 

# Add section for skype creation
#----------------------------------------------
write-host ""
Write-host "Skype Section" -ForegroundColor Green -BackgroundColor Black
write-host "--------------------------------------------------------------------------"




$Skype_Remote_Session = New-PSSession -ConfigurationName Microsoft.Exchange -verbose -ConnectionUri http://DIEPT66EXP0101.air.diep.mil.au/powershell/ -Authentication Kerberos -Credential $userCredential

write-host ""
write-host "Import Remote session " -ForegroundColor Green -BackgroundColor Black
Import-PSsession $Skype_Remote_Session

#For each user in the T2_user.csv file it will check to see if they already have skype account write a message if they do and if not enable their skype account.
foreach ($user in $aduser){
if (Get-ADUser -Filter "proxyAddresses -like ""*$($User)@email.address*""")
{
    write-warning "$user already has a skype account enabled"
}
else
{
    Write-Host "Created Skype SIP for $($User.Username) " -ForegroundColor Green
    Enable-CsUser -Identity "$($subdomain)\$($Username)" -SipAddress "sip:$($Username)@email.address" -RegistrarPool servername -DomainController servername
}
}

# Removes the  skype management shell Remote session from Powershell 
Remove-PSSession -Session $skype_Remote_Session 


#### End of script 

 

 

Problem 2:

For this the script above is running from AD server and we won't be able to install S4B management shell so is their way to do remote session to S4B management shell that's on our skype server. 
or will your PSSession command work for this. 

 

@Hjb118 

What is the output of 

foreach ($user in $aduser){
if (Get-ADUser -Filter "mail -eq ""$($Username)@email.address""")
{
write-host "$Username"
write-host "do nothing"
}
else
{
write-host "$Username"
write-host "create mailbox"
}
}

Do you get a list of users with no email, and is the CSV file include only a list of usernames?

I'll get a list of user that need to be created but sometimes user already exist then we need check see if they have email but if they don't the script below will check if they do and either create the mailbox or not.

I have attached cvs with 3 users, first 2 should Output "do nothing" and last user should output "create mailbox"

My normal cvs file with include all details need to creat each user.

@Hjb118 

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}
}


@farismalaeb 

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
}

 

best response confirmed by Hjb118 (Occasional Contributor)
Solution

@Hjb118 

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.