Solved

Check to see if user exists powershell script.

Posted on 2012-04-11
6
6,583 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
Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

 

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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Windows 10 came with  a lot of built in applications, Some organisations leave them there, some will control them using GPO's. This Article is useful for those who do not want to have any applications in their image (example:me).
This article demonstrates probably the easiest way to configure domain-wide tier isolation within Active Directory. If you do not know tier isolation read https://technet.microsoft.com/en-us/windows-server-docs/security/securing-privileged-access/s…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

749 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