Solved

Check to see if user exists powershell script.

Posted on 2012-04-11
6
6,706 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 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
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

 

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

Technology Partners: 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!

Question has a verified solution.

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

Active Directory security has been a hot topic of late, and for good reason. With 90% of the world’s organization using this system to manage access to all parts of their IT infrastructure, knowing how to protect against threats and keep vulnerabil…
Uncontrolled local administrators groups within any organization pose a huge security risk. Because these groups are locally managed it becomes difficult to audit and maintain them.
The basic steps you have just learned will be implemented in this video. The basic steps are shown to configure an Exchange DAG in a live working Exchange Server Environment and manage the same (Exchange Server 2010 Software is used in a Windows Ser…
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

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