?
Solved

Check to see if user exists powershell script.

Posted on 2012-04-11
6
Medium Priority
?
6,841 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 

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 2000 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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

Office 365 Training for Admins - 7 Day Trial

Learn how to provision tenants, synchronize on-premise Active Directory, implement Single Sign-On, customize Office deployment, and protect your organization with eDiscovery and DLP policies.  Only from Platform Scholar.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Check out this step-by-step guide for using the newly updated Experts Exchange mobile app—released on May 30.
There are times when we need to generate a report on the inbox rules, where users have set up forwarding externally in their mailbox. In this article, I will be sharing a script I wrote to generate the report in CSV format.
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …
Suggested Courses
Course of the Month8 days, 3 hours left to enroll

765 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