Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Check to see if user exists powershell script.

Posted on 2012-04-11
6
Medium Priority
?
7,018 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
Q2 2017 - Latest Malware & Internet Attacks

WatchGuard’s Threat Lab is a group of dedicated threat researchers committed to helping you stay ahead of the bad guys by providing in-depth analysis of the top security threats to your network.  Check out our latest Quarterly Internet Security Report!

 

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

 [eBook] Windows Nano Server

Download this FREE eBook and learn all you need to get started with Windows Nano Server, including deployment options, remote management
and troubleshooting tips and tricks

Question has a verified solution.

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

I don't pretend to be an expert at this, but I have found a few things that are useful. I hope that sharing them here will help others, so they will not have to face some rather hard choices. Since I felt this to be a topic of enough importance and…
Here in this article, you will get a step by step guidance on how to restore an Exchange database to a recovery database. Get a brief on Recovery Database and how it can be used to restore Exchange database in this section!
how to add IIS SMTP to handle application/Scanner relays into office 365.
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…
Suggested Courses

636 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