Solved

Check to see if user exists powershell script.

Posted on 2012-04-11
6
6,155 Views
Last Modified: 2012-04-11
I am looking to add to a powershell script that will check if the user exists. If not then run this script. I just would like to plug that extra part right in. Here is the script.

add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010, Quest.ActiveRoles.ADManagement
Import-Module ActiveDirectory
$Users = Import-Csv C:\temp\UsersPS.csv

#Create a bulk mailboxes
Foreach ($User in $Users){

#Create a Mail-Enabled User
New-Mailbox -Name ($User.sn + ", " + $User.givenName) -FirstName $User.givenName -LastName $User.sn -Alias $User.alias `
-UserPrincipalName ($user.alias +'@mtnbrook.loc') -Database $User.Database -RetentionPolicy MBSPolicy -OrganizationalUnit $User.OU `
-Password ( ConvertTo-SecureString $User.password -AsPlainText -Force) -ResetPasswordOnNextLogon:$false `
-ErrorVariable err | Out-Null
Add-MailboxPermission -Identity $user.alias -User "Mailbox Administrators" -AccessRights FullAccess -Automapping $false


#Check AD Latency
do
{
 $mailbox = Get-Mailbox -Identity $user.alias -ErrorAction SilentlyContinue
}
While ($mailbox -eq $null)

#Modify attributes of User's account properties
Set-QADUser -Identity $user.alias -Description $user.alias -Company $user.Company -Initials $user.Initials -Title $user.Title -HomeDirectory $user.homeDirectory `
-Office $User.office -HomeDrive G: -PasswordNeverExpires:$true
Add-QADPermission -Identity $user.alias -Account SELF,Everyone -Extendedright "User-Change-Password" -Deny -ApplyTo ThisObjectOnly
Add-ADGroupMember -Identity $user.Group -Member $user.alias
}
0
Comment
Question by:falconcurt
  • 3
  • 2
6 Comments
 
LVL 17

Expert Comment

by:Anuroopsundd
ID: 37832104
0
 

Author Comment

by:falconcurt
ID: 37832175
Still not sure how i would actually implement that in this script.
0
 
LVL 6

Accepted Solution

by:
NikolasG earned 500 total points
ID: 37832244
Hi,
I think that the following should do what you ask
Import-Module ActiveDirectory
$Users = Import-Csv C:\temp\UsersPS.csv

#Create a bulk mailboxes
Foreach ($User in $Users){

#check if the user exists
$Status = (Check-ADUser -username $User).Status
If ($Status -eq 1)
{
    write-host("$User exists.")
} Else {
    write-host("$User does not exists creating mail.")
	#Create a Mail-Enabled User
	New-Mailbox -Name ($User.sn + ", " + $User.givenName) -FirstName $User.givenName -LastName $User.sn -Alias $User.alias `
	-UserPrincipalName ($user.alias +'@mtnbrook.loc') -Database $User.Database -RetentionPolicy MBSPolicy -OrganizationalUnit $User.OU `
	-Password ( ConvertTo-SecureString $User.password -AsPlainText -Force) -ResetPasswordOnNextLogon:$false `
	-ErrorVariable err | Out-Null
	Add-MailboxPermission -Identity $user.alias -User "Mailbox Administrators" -AccessRights FullAccess -Automapping $false


	#Check AD Latency
	do
	{
		$mailbox = Get-Mailbox -Identity $user.alias -ErrorAction SilentlyContinue
	}
	While ($mailbox -eq $null)

	#Modify attributes of User's account properties
	Set-QADUser -Identity $user.alias -Description $user.alias -Company $user.Company -Initials $user.Initials -Title $user.Title -HomeDirectory $user.homeDirectory `
	-Office $User.office -HomeDrive G: -PasswordNeverExpires:$true
	Add-QADPermission -Identity $user.alias -Account SELF,Everyone -Extendedright "User-Change-Password" -Deny -ApplyTo ThisObjectOnly
	Add-ADGroupMember -Identity $user.Group -Member $user.alias
	}
}

Function Check-ADUser
{
    Param ($Username)
 
    $Username = ($Username.Split("\")[1])
    $ADCompletePath = "LDAP://"+$ADServer+":"+$ADPort+"/DC="+$D1name+",DC="+$D2name
    $ADRoot =  [ADSI]'"$ADCompletePath"'

    $ADSearch = New-Object System.DirectoryServices.DirectorySearcher($ADRoot)  
    $SAMAccountName = "$Username"
    $ADSearch.Filter = "(&(objectClass=user)(sAMAccountName=$SAMAccountName))"
    $Result = $ADSearch.FindAll()
 
    If($Result.Count -eq 0)
    {
        $Status = "0"
    }
    Else
    {
        $Status = "1"
    }
     
    $Results = New-Object Psobject
    $Results | Add-Member Noteproperty Status $Status
    Write-Output $Results     
}

Open in new window


Please feed back.
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:falconcurt
ID: 37832499
For some reason it is not recognizing check-aduser. I have used the import-module activedirectory but still does not recognize command check-aduser. Am i missing something?
0
 

Author Comment

by:falconcurt
ID: 37832687
I got it to work when i changed the location of the function statement. I move it to the top and it worked. Thanks!
0
 
LVL 6

Expert Comment

by:NikolasG
ID: 37832952
Try the following
Import-Module ActiveDirectory
$Users = Import-Csv C:\temp\UsersPS.csv
#Ask for the primary domain controler on which it's going to check the names
$ADServer=Read-host -prompt "`nPlease enter the AD Server name [NetBIOS name]:"

#Using WMI object to retrieve the domain name
$ADDomainName=(Get-WmiObject Win32_ComputerSystem).Domain

#Splitting the domain name a.com to a and com
$D1name=($ADDomainName.Split(".")[0])
$D2name=($ADDomainName.Split(".")[1])

Function Check-ADUser
{
    Param ($Username)
 
    $Username = ($Username.Split("\")[1])
    $ADCompletePath = "LDAP://"+$ADServer+":389"+"/DC="+$D1name+",DC="+$D2name
    $ADRoot =  [ADSI]'"$ADCompletePath"'

    $ADSearch = New-Object System.DirectoryServices.DirectorySearcher($ADRoot)  
    $SAMAccountName = "$Username"
    $ADSearch.Filter = "(&(objectClass=user)(sAMAccountName=$SAMAccountName))"
    $Result = $ADSearch.FindAll()
 
    If($Result.Count -eq 0)
    {
        $Status = "0"
    }
    Else
    {
        $Status = "1"
    }
     
    $Results = New-Object Psobject
    $Results | Add-Member Noteproperty Status $Status
    Write-Output $Results     
}


#Create a bulk mailboxes
Foreach ($User in $Users){

#check if the user exists
$Status = (Check-ADUser -username $User.sn).Status
If ($Status -eq 1)
{
    write-host("$User exists.")
} Else {
    write-host("$User does not exists creating mail.")
	#Create a Mail-Enabled User
	New-Mailbox -Name ($User.sn + ", " + $User.givenName) -FirstName $User.givenName -LastName $User.sn -Alias $User.alias `
	-UserPrincipalName ($user.alias +'@mtnbrook.loc') -Database $User.Database -RetentionPolicy MBSPolicy -OrganizationalUnit $User.OU `
	-Password ( ConvertTo-SecureString $User.password -AsPlainText -Force) -ResetPasswordOnNextLogon:$false `
	-ErrorVariable err | Out-Null
	Add-MailboxPermission -Identity $user.alias -User "Mailbox Administrators" -AccessRights FullAccess -Automapping $false


	#Check AD Latency
	do
	{
		$mailbox = Get-Mailbox -Identity $user.alias -ErrorAction SilentlyContinue
	}
	While ($mailbox -eq $null)

	#Modify attributes of User's account properties
	Set-QADUser -Identity $user.alias -Description $user.alias -Company $user.Company -Initials $user.Initials -Title $user.Title -HomeDirectory $user.homeDirectory `
	-Office $User.office -HomeDrive G: -PasswordNeverExpires:$true
	Add-QADPermission -Identity $user.alias -Account SELF,Everyone -Extendedright "User-Change-Password" -Deny -ApplyTo ThisObjectOnly
	Add-ADGroupMember -Identity $user.Group -Member $user.alias
	}
}

Open in new window

0

Featured Post

Want to promote your upcoming event?

Are you going to an event? Are you going to be exhibiting at a tradeshow? Talking at a conference? Using a promotional banner in your email signature ensures that your organization’s most important contacts stay in the know and can potentially spread the word about the event.

Join & Write a Comment

Exchange server is not supported in any cloud-hosted platform (other than Azure with Azure Premium Storage).
This article explains how to prepare an HTML email signature template file containing dynamic placeholders for users' Azure AD data. Furthermore, it explains how to use this file to remotely set up a department-wide email signature policy in Office …
In this video we show how to create a Shared Mailbox in Exchange 2013. We show this process by using the Exchange Admin Center. Log into Exchange Admin Center.: First we need to log into the Exchange Admin Center. Navigate to the Recipients >> Sha…
In this video we show how to create a mailbox database in Exchange 2013. We show this process by using the Exchange Admin Center. Log into Exchange Admin Center.: First we need to log into the Exchange Admin Center. Navigate to the Servers >> Data…

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now