Hello PowerShell gurus,
I am done with creation and addition of variables in a powershell script with does AD creation and Mailbox creation from CSV.
However, sometimes it creates the mailbox with no error, generally for first AD user in csv, sometimes it does not and rest of the script also ends with no configuration of fields.
It gives an error "Oops, something went wrong: Cannot find an object with identity:". Can you please review my modified script once and guide me.
I would be really thankful to you. I thank you for your kind guidance.
P.S.:I am not a master of scripting, so could not find anything more in it. I believe #create mailbox piece has some issue, I have made it bold, can you please check once.
Warm Regards,
Gautam
Script
==========================================================
###########################################################
# AUTHOR : GAUTAM VERMA
# DATE : 23-07-2015
# EDIT : 23-07-2015
# COMMENT : This script creates new Active Directory users,
# including different kind of properties, based
# on an input_create_ad_users.csv.
# VERSION : 1.3
###########################################################
# CHANGELOG
# Version 1.2: 20-07-2015 - Changed the code for better
# - Added better Error Handling and Reporting.
# - Changed input file with more logical headers.
# - Added functionality for account Enabled,
# PasswordNeverExpires, ProfilePath, ScriptPath,
# HomeDirectory and HomeDrive
# - Added the option to move every user to a different OU.
# Version 1.3: 23-07-2015
# ERROR REPORTING ALL
Set-StrictMode -Version latest
#----------------------------------------------------------
# LOAD ASSEMBLIES AND MODULES
#----------------------------------------------------------
Try
{
Import-Module ActiveDirectory -ErrorAction Stop
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
}
Catch
{
Write-Host "[ERROR]`t ActiveDirectory Module couldn't be loaded. Script will stop!"
Exit 1
}
#----------------------------------------------------------
#STATIC VARIABLES
#----------------------------------------------------------
$path = Split-Path -parent $MyInvocation.MyCommand.Definition
$newpath = $path + "\import_create_ad_users.csv"
$log = $path + "\create_ad_users.log"
$date = Get-Date
$addn = (Get-ADDomain).DistinguishedName
$dnsroot = (Get-ADDomain).DNSRoot
$i = 1
#----------------------------------------------------------
#START FUNCTIONS
#----------------------------------------------------------
Function Start-Commands
{
Create-Users
}
Function Create-Users
{
"Processing started (on " + $date + "): " | Out-File $log -append"--------------------------------------------" | Out-File $log -append
Import-CSV $newpath | ForEach-Object {
If (($_.Implement.ToLower()) -eq "yes")
{
If (($_.GivenName -eq "") -Or ($_.LastName -eq ""))
{
Write-Host "[ERROR]`t Please provide valid GivenName, LastName and Initials. Processing skipped for line $($i)`r`n""[ERROR]`t Please provide valid GivenName, LastName and Initials. Processing skipped for line $($i)`r`n" | Out-File $log -append
}
Else
{
# Set the target OU
$location = $_.TargetOU + ",$($addn)"
# Set the Enabled and PasswordNeverExpires properties
If (($_.Enabled.ToLower()) -eq "true") { $enabled = $True } Else { $enabled = $False }
If (($_.PasswordNeverExpires.ToLower()) -eq "true") { $expires = $True } Else { $expires = $False }
# A check for the country, because those were full names and need
# to be land codes in order for AD to accept them. I used India
# as example
If($_.Country -eq "India")
{
$_.Country = "IN"
}
Else
{
$_.Country = "US"
}
# Replace dots / points (.) in names, because AD will error when a
# name ends with a dot (and it looks cleaner as well)
$replace = $_.Lastname.Replace(".","")
If($replace.length -lt 4)
{
$lastname = $replace
}
Else
{
$lastname = $replace.substring(0,4)
}
# Create sAMAccountName according to this 'naming convention':
# <FirstLetterGivenName><FirstThreeLettersLastName><Last3digitsOfSSN> for example
# Gverm
$sam = $_.GivenName.substring(0,1).ToLower() + $lastname.substring(0,3).ToLower() +$_.SSN.substring(0,3).ToLower()
Try { $exists = Get-ADUser -LDAPFilter "(sAMAccountName=$sam)" }
Catch { }
If(!$exists)
{
# Set all variables according to the table names in the Excel
# sheet / import CSV. The names can differ in every project, but
# if the names change, make sure to change it below as well.
$setpass = ConvertTo-SecureString -AsPlainText $_.Password -force
Try
{
Write-Host "[INFO]`t Creating user : $($sam)""[INFO]`t Creating user : $($sam)" | Out-File $log -append
New-ADUser $sam -GivenName $_.GivenName `
-Surname $_.LastName -DisplayName ($_.LastName + "," + $_.GivenName) `
-Office $_.OfficeName -Description $_.Description -EmailAddress $_.Mail `
-StreetAddress $_.StreetAddress -City $_.City -State $_.State `
-PostalCode $_.PostalCode -Country $_.Country -UserPrincipalName ($sam + "@" + $dnsroot) `
-Company $_.Company -Department $_.Department -EmployeeID $_.EmployeeID `
-Title $_.Title -OfficePhone $_.Phone -AccountPassword $setpass -Manager $_.Manager `
-profilePath $_.ProfilePath -scriptPath $_.ScriptPath -homeDirectory $_.HomeDirectory `
-homeDrive $_.homeDrive -Enabled $enabled -PasswordNeverExpires $expires -ChangePasswordAtLogon $True
Write-Host "[INFO]`t Created new user : $($sam)""[INFO]`t Created new user : $($sam)" | Out-File $log -append
$dn = (Get-ADUser $sam).DistinguishedName
# Set an ExtensionAttribute
If ($_.ExtensionAttribute1 -ne "" -And $_.ExtensionAttribute1 -ne $Null)
{
$ext = [ADSI]"LDAP://$dn"
$ext.Put("extensionAttribute1", $_.ExtensionAttribute1)
Try { $ext.SetInfo() }
Catch { Write-Host "[ERROR]`t Couldn't set the Extension Attribute : $($_.Exception.Message)" }
}
#Create Home Directory
$HomeDriveLetter=’I:’
$UserRoot=("\\"+$_.HomeServer+"\e$\Users\")
$HomeDirectoryPath=$UserRoot+$sam
New-Item $HomeDirectoryPath -Type directory -force
SET-ADUSER $sam –HomeDrive $HomeDriveLetter –HomeDirectory $HomeDirectoryPath
$Acl = Get-ACL $HomeDirectoryPath
$AccessRule= New-Object System.Security.AccessControl.FileSystemAccessRule("self","FullControl","ContainerInherit,Objectinherit","none","Allow")
$Acl.AddAccessRule($AccessRule)
Set-Acl $HomeDirectoryPath $Acl
#Copy items from Share location to Home Drive
Copy-Item \\covtech1\Software\Applications\HOMEDIR\* $HomeDirectoryPath
# Move the user to the OU ($location) you set above. If you don't
# want to move the user(s) and just create them in the global Users
# OU, comment the string below
If ([adsi]::Exists("LDAP://$($location)"))
{
Move-ADObject -Identity $dn -TargetPath $location
Write-Host "[INFO]`t User $sam moved to target OU : $($location)""[INFO]`t User $sam moved to target OU : $($location)" | Out-File $log -append
}
Else
{
Write-Host "[ERROR]`t Targeted OU couldn't be found. Newly created user wasn't moved!""[ERROR]`t Targeted OU couldn't be found. Newly created user wasn't moved!" | Out-File $log -append
}
#To add user to all the Groups which other user is memberof.It is can be normally used when new user needs to have all the group membership of the existing users
$Name = $_.mirror
$groups = (GET-ADUSER –Identity $Name –Properties MemberOf).MemberOf
foreach ($group in $groups) {
Add-ADGroupMember -Identity $group -Members $sam
}
$count = $groups.count
# Remote Desktop Services Profile
$dn = (Get-ADUser $sam).DistinguishedName
$ext = [ADSI]"LDAP://$dn"
$ext.PSBase.invokeSet("TerminalServicesProfilePath","\\PROFILETHIN1\PROFILETHIN1$\$sam.%OSNAME%")
$ext.SetInfo()#create Mailbox
Write-Host "`nCreating mailbox for [$sam] on CBT-DB2" -ForegroundColor Cyan
Start-Sleep -s 10
$disname = (Get-ADUser $sam).DistinguishedName
Try {Enable-Mailbox $disname -Database CBT-DB2 -ErrorAction Stop}
Catch {
If ($_.Exception.Message -like '*is of type User*') {
Write-Host `t "[$sam] already has a mailbox, continuing to next step " -ForegroundColor Yellow}
Else {Write-Host "Proceeding to Next step" -ForegroundColor Green}}
# Rename the object to a good looking name (otherwise you see
# the 'ugly' shortened sAMAccountNames as a name in AD. This
# can't be set right away (as sAMAccountName) due to the 20
# character restriction
Write-Host "[INFO]`t Renamed $($sam) to $($_.GivenName) $($_.LastName)`r`n""[INFO]`t Renamed $($sam) to $($_.GivenName) $($_.LastName)`r`n" | Out-File $log -append
}
Catch
{
Write-Host "[ERROR]`t Oops, something went wrong: $($_.Exception.Message)`r`n"
}
}
Else
{
Write-Host "[SKIP]`t User $($sam) ($($_.GivenName) $($_.LastName)) already exists or returned an error!`r`n""[SKIP]`t User $($sam) ($($_.GivenName) $($_.LastName)) already exists or returned an error!" | Out-File $log -append
}
}
}
Else
{
Write-Host "[SKIP]`t User ($($_.GivenName) $($_.LastName)) will be skipped for processing!`r`n""[SKIP]`t User ($($_.GivenName) $($_.LastName)) will be skipped for processing!" | Out-File $log -append
}
$i++
}"--------------------------------------------" + "`r`n" | Out-File $log -append
}
Write-Host "STARTED SCRIPT`r`n"
Start-Commands
Write-Host "STOPPED SCRIPT"
==========================================================