Solved

Creating bulk users and making changes from CSV file using powershell

Posted on 2015-02-18
14
369 Views
Last Modified: 2016-11-23
I am attempting to edit my powershell script that was originally created to work with Exchange 2010 and using the Quest cmdlets. Unfortunately, Dell has make them more difficult to install on my new exchanges. The problem is that i am getting several different errors pop up when i run the script.

G
add-PSSnapin Microsoft.Exchange.Managem<wbr ></wbr>ent.PowerS<wbr ></wbr>hell.SnapI<wbr ></wbr>n
Import-Module ActiveDirectory
$Users = Import-Csv \\testserver1\c$\temp\Crea<wbr ></wbr>teStaff\Us<wbr ></wbr>ersPS.csv

Function Check-ADUser
{
     Param ($Username)
  
     $Username = $Username.Split("\")
     $ADRoot =  [ADSI]''
     $ADSearch = New-Object System.DirectoryServiTEST3<wbr ></wbr>.Directory<wbr ></wbr>Searcher($<wbr ></wbr>ADRoot)  
     $SAMAccountName = "$Username"
     $ADSearch.Filter = "(&(objectClass=user)(sAMA<wbr ></wbr>ccountName<wbr ></wbr>=$SAMAccou<wbr ></wbr>ntName))"
     $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
}

$Users = Import-Csv \\testserver1\c$\temp\Crea<wbr ></wbr>teStaff\Us<wbr ></wbr>ersPS.csv
$TEST4StaffOU = "OU=Staff,OU=School Users,OU=TEST4,OU=District<wbr ></wbr> Schools,DC=domain,DC=loc"
$TEST4UsersOU = "OU=Users,OU=School Users,OU=TEST4,OU=District<wbr ></wbr> Schools,DC=domain,DC=loc"
$TEST4OfficeOU = "OU=Office,OU=School Users,OU=TEST4,OU=District<wbr ></wbr> Schools,DC=domain,DC=loc"
$TEST3StaffOU = "OU=Staff,OU=School Users,OU=TEST3,OU=District<wbr ></wbr> Schools,DC=domain,DC=loc"
$TEST3UsersOU = "OU=Users,OU=School Users,OU=TEST3,OU=District<wbr ></wbr> Schools,DC=domain,DC=loc"
$TEST3OfficeOU = "OU=Office,OU=School Users,OU=TEST3,OU=District<wbr ></wbr> Schools,DC=domain,DC=loc"
$TEST1StaffOU = "OU=Staff,OU=School Users,OU=TEST1,OU=District<wbr ></wbr> Schools,DC=domain,DC=loc"
$TEST1UsersOU = "OU=Users,OU=School Users,OU=TEST1,OU=District<wbr ></wbr> Schools,DC=domain,DC=loc"
$TEST1OfficeOU = "OU=Office,OU=School Users,OU=TEST1,OU=District<wbr ></wbr> Schools,DC=domain,DC=loc"
$TEST5StaffOU = "OU=Staff,OU=School Users,OU=TEST5,OU=District<wbr ></wbr> Schools,DC=domain,DC=loc"
$TEST5UsersOU = "OU=Users,OU=School Users,OU=TEST5,OU=District<wbr ></wbr> Schools,DC=domain,DC=loc"
$TEST5OfficeOU = "OU=Office,OU=School Users,OU=TEST5,OU=District<wbr ></wbr> Schools,DC=domain,DC=loc"
$TEST2StaffOU = "OU=Staff,OU=School Users,OU=TEST2,OU=District<wbr ></wbr> Schools,DC=domain,DC=loc"
$TEST2UsersOU = "OU=Users,OU=School Users,OU=TEST2,OU=District<wbr ></wbr> Schools,DC=domain,DC=loc"
$TEST2OfficeOU = "OU=Office,OU=School Users,OU=TEST2,OU=District<wbr ></wbr> Schools,DC=domain,DC=loc"
$TEST5StaffOU = "OU=Staff,OU=School Users,OU=TEST5,OU=District<wbr ></wbr> Schools,DC=domain,DC=loc"
$TEST5UsersOU = "OU=Users,OU=School Users,OU=TEST5,OU=District<wbr ></wbr> Schools,DC=domain,DC=loc"
$TEST5OfficeOU = "OU=Office,OU=School Users,OU=TEST5,OU=District<wbr ></wbr> Schools,DC=domain,DC=loc"
$logfile = "\\testserver1\c$\Temp\Cre<wbr ></wbr>ateStaff\s<wbr ></wbr>taff.html"<wbr ></wbr>
Write-Host "Creating new Log file" | Out-File $logfile

#Create a bulk mailboxes
Foreach ($User in $Users){


#check if the user exists
$Status = (Check-ADUser -username $User.alias.Trim()).Status<wbr ></wbr>
If ($Status -eq 1)
{
    write-host("$User exists.")
} Else {
    Write-Host "$($User.alias) does not exists creating account." -ForegroundColor Yellow
        "<br>$($User.alias) does not exists creating account.<br>" | add-content $logfile
      #Create a Mail-Enabled User
      New-Mailbox -Name ($User.LastName.Trim() + ", " + $User.Firstname.Trim()) -FirstName $User.Firstname.Trim() -LastName $User.LastName.Trim() -Alias $User.alias.Trim() `
      -UserPrincipalName ($user.alias.Trim() +'@domain.loc') -RetentionPolicy 123Policy `
      -Password ( ConvertTo-SecureString $User.password.Trim() -AsPlainText -Force) -ResetPasswordOnNextLogon:<wbr ></wbr>$true `
      -ErrorVariable err | Out-Null
      Add-MailboxPermission -Identity $user.alias.Trim() -User "Mailbox Administrators" -AccessRights FullAccess -Automapping $false
    
#Map users home directory
    $Homedir = $User.Company
    Switch ($HomeDir)
	   {
        TEST4 {$UserHomedir = "\\TEST4-dataserv\staff\" + $User.alias; break}
	    TEST1 {$UserHomedir = "\\TEST1-dataserv\staff\" + $User.alias; break}
	    TEST3 {$UserHomedir = "\\TEST3-dataserv\staff\" + $User.alias; break}
	    TEST2 {$UserHomedir = "\\TEST2-dataserv\staff\" + $User.alias; break}
	    TEST5 {$UserHomeDir = "\\TEST5-dataserv\staff\" + $User.alias; break}
	    TEST5 {$UserHomeDir = "\\TEST5-dataserv\staff\" + $User.alias; break}
        }
#Check AD Latency
      do
      {
            $mailbox = Get-Mailbox -Identity $user.alias -ErrorAction SilentlyContinue
      }
      While ($mailbox -eq $null)

#Modify attributes of User's account properties
    $GetUser = (Get-ADUser -Identity $Users.Alias).distinguishe<wbr ></wbr>dName
       $GetUser | Set-ADUser -Description $user.alias -City ($User.Alias + "@student.domain.k12.al.us<wbr ></wbr>") -Company $user.Company -Initials $user.Initials -HomeDrive G: -Title $user.Title -HomeDirectory ($UserHomedir + "\documents") `
      -Office $User.Company -PasswordNeverExpires:$fal<wbr ></wbr>se
       Add-Content $logfile -Value "<br>`n$($User.alias) account created.<br>" -encoding Utf8

#Move users to correct databases
   $MoveDatabase = $User.Database
    Switch ($MoveDatase)
    {
        {($User.Title -eq "Office")} {New-MoveRequest -Identity $User.Alias -TargetDatabase "123 Office"; break}
        {($User.Title -eq "Staff")} {New-MoveRequest -Identity $User.Alias -TargetDatabase "123 Staff 2"; break}
        {($User.Title -eq "Users")} {New-MoveRequest -Identity $User.Alias -TargetDatabase "123 Staff 2"; break}
        }
#Add users to groups
    $AddGroup = $User.Title, $User.Company
    Switch ($AddGroup)
    {
        {($User.Title -eq "STAFF") -and ($User.Company -eq "TEST4")} {Add-ADGroupMeTEST4r -Identity "TEST4 Staff" -MeTEST4r $user.alias; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "TEST4")} {Add-ADGroupMeTEST4r -Identity "TEST4 Office" -MeTEST4r $user.alias; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "TEST4")} {Add-ADGroupMeTEST4r -Identity "TEST4 Users" -MeTEST4r $user.alias; break}
        {($User.Title -eq "STAFF") -and ($User.Company -eq "TEST3")} {Add-ADGroupMeTEST4r -Identity "TEST3 Staff" -MeTEST4r $user.alias; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "TEST3")} {Add-ADGroupMeTEST4r -Identity "TEST3 Office" -MeTEST4r $user.alias; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "TEST3")} {Add-ADGroupMeTEST4r -Identity "TEST3 Users" -MeTEST4r $user.alias; break}
        {($User.Title -eq "STAFF") -and ($User.Company -eq "TEST1")} {Add-ADGroupMeTEST4r -Identity "TEST1 Staff" -MeTEST4r $user.alias; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "TEST1")} {Add-ADGroupMeTEST4r -Identity "TEST1 Office" -MeTEST4r $user.alias; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "TEST1")} {Add-ADGroupMeTEST4r -Identity "TEST1 Users" -MeTEST4r $user.alias; break}
        {($User.Title -eq "STAFF") -and ($User.Company -eq "TEST2")} {Add-ADGroupMeTEST4r -Identity "TEST2 Staff" -MeTEST4r $user.alias; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "TEST2")} {Add-ADGroupMeTEST4r -Identity "TEST2 Office" -MeTEST4r $user.alias; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "TEST2")} {Add-ADGroupMeTEST4r -Identity "TEST2 Users" -MeTEST4r $user.alias; break}
        {($User.Title -eq "STAFF") -and ($User.Company -eq "TEST5")} {Add-ADGroupMeTEST4r -Identity "TEST5 Staff" -MeTEST4r $user.alias; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "TEST5")} {Add-ADGroupMeTEST4r -Identity "TEST5 Office" -MeTEST4r $user.alias; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "TEST5")} {Add-ADGroupMeTEST4r -Identity "TEST5 Users" -MeTEST4r $user.alias; break}
        {($User.Title -eq "STAFF") -and ($User.Company -eq "TEST5")} {Add-ADGroupMeTEST4r -Identity "TEST5 Staff" -MeTEST4r $user.alias; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "TEST5")} {Add-ADGroupMeTEST4r -Identity "TEST5 Office" -MeTEST4r $user.alias; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "TEST5")} {Add-ADGroupMeTEST4r -Identity "TEST5 Users" -MeTEST4r $user.alias; break}
        }


#Move users to correct OU.  
    $OUMove =  $User.Title, $User.Company
    Switch ($OUMove)
    {
        {($User.Title -eq "STAFF") -and ($User.Company -eq "TEST4")} {Move-ADObject -Identity $GetUser -identity $GetUser -TargetPath $TEST4STAFFOU; break}
        {($User.Title -eq "STAFF") -and ($User.Company -eq "TEST3")} {Move-ADObject -Identity $GetUser -TargetPath $TEST3STAFFOU; break}
        {($User.Title -eq "STAFF") -and ($User.Company -eq "TEST1")} {Move-ADObject -Identity $GetUser -TargetPath $TEST1STAFFOU; break}
        {($User.Title -eq "STAFF") -and ($User.Company -eq "TEST2")} {Move-ADObject -Identity $GetUser -TargetPath $TEST2STAFFOU; break}
        {($User.Title -eq "STAFF") -and ($User.Company -eq "TEST5")} {Move-ADObject -Identity $GetUser -TargetPath $TEST5STAFFOU; break}
        {($User.Title -eq "STAFF") -and ($User.Company -eq "TEST5")} {Move-ADObject -Identity $GetUser -TargetPath $TEST5StaffOU; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "TEST4")} {Move-ADObject -Identity $GetUser -TargetPath $TEST4USERSOU; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "TEST3")} {Move-ADObject -Identity $GetUser -TargetPath $TEST3USERSOU; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "TEST1")} {Move-ADObject -Identity $GetUser -TargetPath $TEST1USERSOU; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "TEST5")} {Move-ADObject -Identity $GetUser -TargetPath $TEST5USERSOU; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "TEST5")} {Move-ADObject -Identity $GetUser -TargetPath $TEST5USERSOU; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "TEST2")} {Move-ADObject -Identity $GetUser -TargetPath $TEST2USERSOU; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "TEST4")} {Move-ADObject -Identity $GetUser -TargetPath $TEST4OFFICEOU; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "TEST3")} {Move-ADObject -Identity $GetUser -TargetPath $TEST3OFFICEOU; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "TEST1")} {Move-ADObject -Identity $GetUser -TargetPath $TEST1OFFICEOU; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "TEST2")} {Move-ADObject -Identity $GetUser -TargetPath $TEST2OFFICEOU; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "TEST5")} {Move-ADObject -Identity $GetUser -TargetPath $TEST5OFFICOU; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "TEST5")} {Move-ADObject -Identity $GetUser -TargetPath $TEST5OFFICEOU; break}

    }
      }

#Add Home Directories


  if (!(Test-Path $Userhomedir)) {
    $homepath = ($Userhomedir + "\documents")
    New-Item $homepath -type directory 
    $acl = Get-Acl $Userhomedir
    $userval = $User.alias + "@domain.loc"
    $Acl.SetAccessRuleProtecti<wbr ></wbr>on($false,<wbr ></wbr> $True)
    $rule = New-Object System.Security.AccessCont<wbr ></wbr>rol.FileSy<wbr ></wbr>stemAcTEST<wbr ></wbr>3sRule($us<wbr ></wbr>erval,'Ful<wbr ></wbr>lControl',<wbr ></wbr>'Container<wbr ></wbr>Inherit, ObjectInherit', 'None', 'Allow')
    $Acl.AddAccessRule($rule)
    $acl.SetAccessRule($access<wbr ></wbr>Rule)
    Set-Acl $Userhomedir $Acl
   }
} 

$body = Get-Content ("\\testserver1\c$\Temp\Cr<wbr ></wbr>eateStaff\<wbr ></wbr>staff.html<wbr ></wbr>") 
Send-mailMessage -From "admin@domain.com" -To "test@domain.com" -Subject "teacher account creation log" -Body ($body | Out-string) -bodyashtml:$true -smtpserver mail.domain.com

Open in new window

et-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null or an element of the argument collection
contains a null value.
At C:\Temp\CreateStaff\Add-Mailbox.ps1:89 char:38
+     $GetUser = (Get-ADUser -Identity $_.Alias).distinguishedName
+                                      ~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser
 
Set-ADUser : Directory object not found
At C:\Temp\CreateStaff\Add-Mailbox.ps1:90 char:19
+        $GetUser | Set-ADUser -Description $user.alias -City ($User.Alias + "@stu ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (CN=MIMBS\, EMIL...domain,DC=loc:ADUser) [Set-ADUser], ADIdentityNotFoundExce
   ption
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsof
   t.ActiveDirectory.Management.Commands.SetADUser
 
New-MoveRequest : The call to 'net.tcp://server.domain.loc/Microsoft.Exchange.MailboxReplicationService' failed because no
service was listening on the specified endpoint. Error details: Could not connect to
net.tcp://server.domain.loc/Microsoft.Exchange.MailboxReplicationService. The connection attempt lasted for a time span of
00:00:02.0156802. TCP error code 10061: No connection could be made because the target machine actively refused it [::1]:808.
 --> No connection could be made because the target machine actively refused it [::1]:808
At C:\Temp\CreateStaff\Add-Mailbox.ps1:99 char:38
+         {($User.Title -eq "Staff")} {New-MoveRequest -Identity $User.Alias -Targ ...
+                                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [New-MoveRequest], EndpointNotFoundTransientException
    + FullyQualifiedErrorId : [Server=server,RequestId=e215a5d1-10b7-4dad-b46f-ea7bca1c5e76,TimeStamp=2/18/2015 9:33:58 PM] [
   FailureCategory=Cmdlet-EndpointNotFoundTransientException] E7347A14,Microsoft.Exchange.Management.RecipientTasks.NewMoveR  
  equest
 
Move-ADObject : Cannot bind parameter because parameter 'Identity' is specified more than once. To provide multiple values to
parameters that can accept multiple values, use the array syntax. For example, "-parameter value1,value2,value3".
At C:\Temp\CreateStaff\Add-Mailbox.ps1:131 char:102
+ ... ntity $GetUser -identity $GetUser -TargetPath $testSTAFFOU; break}
+                    ~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Move-ADObject], ParameterBindingException
    + FullyQualifiedErrorId : ParameterAlreadyBound,Microsoft.ActiveDirectory.Management.Commands.MoveADObject
0
Comment
Question by:falconcurt
  • 8
  • 6
14 Comments
 
LVL 39

Expert Comment

by:footech
ID: 40617917
Your posted code isn't the same as what you posted errors for.  I don't know how much has changed, but certainly some has (like line 89).
In your posted code, line 89 should be $user instead of $users.
The error for line 90 was because of the previous one.
The error for line 131 is just as it says, you've specified the -identity parameter more than once.
0
 

Author Comment

by:falconcurt
ID: 40618845
I apologize, i had several windows up with the same cold. Here is the code that i verified should be the correct one.
add-PSSnapin Microsoft.Exchange.Management.PowerShell.SnapIn
Import-Module ActiveDirectory
$Users = Import-Csv \\server1\c$\temp\CreateStaff\UsersPS.csv

Function Check-ADUser
{
     Param ($Username)
  
     $Username = $Username.Split("\")
     $ADRoot =  [ADSI]''
     $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
}

$Users = Import-Csv \\server1\c$\temp\CreateStaff\UsersPS.csv
$Test3StaffOU = "OU=Staff,OU=School Users,OU=Test3,OU=District Schools,DC=domain,DC=loc"
$Test3UsersOU = "OU=Users,OU=School Users,OU=Test3,OU=District Schools,DC=domain,DC=loc"
$Test3OfficeOU = "OU=Office,OU=School Users,OU=Test3,OU=District Schools,DC=domain,DC=loc"
$Test1StaffOU = "OU=Staff,OU=School Users,OU=Test1,OU=District Schools,DC=domain,DC=loc"
$Test1UsersOU = "OU=Users,OU=School Users,OU=Test1,OU=District Schools,DC=domain,DC=loc"
$Test1OfficeOU = "OU=Office,OU=School Users,OU=Test1,OU=District Schools,DC=domain,DC=loc"
$Test2StaffOU = "OU=Staff,OU=School Users,OU=Test2,OU=District Schools,DC=domain,DC=loc"
$Test2UsersOU = "OU=Users,OU=School Users,OU=Test2,OU=District Schools,DC=domain,DC=loc"
$Test2OfficeOU = "OU=Office,OU=School Users,OU=Test2,OU=District Schools,DC=domain,DC=loc"
$Test4StaffOU = "OU=Staff,OU=School Users,OU=Test4,OU=District Schools,DC=domain,DC=loc"
$Test4UsersOU = "OU=Users,OU=School Users,OU=Test4,OU=District Schools,DC=domain,DC=loc"
$Test4OfficeOU = "OU=Office,OU=School Users,OU=Test4,OU=District Schools,DC=domain,DC=loc"
$Test6StaffOU = "OU=Staff,OU=School Users,OU=Test6,OU=District Schools,DC=domain,DC=loc"
$Test6UsersOU = "OU=Users,OU=School Users,OU=Test6,OU=District Schools,DC=domain,DC=loc"
$Test6OfficeOU = "OU=Office,OU=School Users,OU=Test6,OU=District Schools,DC=domain,DC=loc"
$Test5StaffOU = "OU=Staff,OU=School Users,OU=Test5,OU=District Schools,DC=domain,DC=loc"
$Test5UsersOU = "OU=Users,OU=School Users,OU=Test5,OU=District Schools,DC=domain,DC=loc"
$Test5OfficeOU = "OU=Office,OU=School Users,OU=Test5,OU=District Schools,DC=domain,DC=loc"
$logfile = "\\server1\c$\Temp\CreateStaff\staff.html"
Write-Host "Creating new Log file" | Out-File $logfile

#Create a bulk mailboxes
Foreach ($User in $Users){


#check if the user exists
$Status = (Check-ADUser -username $User.alias.Trim()).Status
If ($Status -eq 1)
{
    write-host("$User exists.")
} Else {
    Write-Host "$($User.alias) does not exists creating account." -ForegroundColor Yellow
        "<br>$($User.alias) does not exists creating account.<br>" | add-content $logfile
      #Create a Mail-Enabled User
      New-Mailbox -Name ($User.LastName.Trim() + ", " + $User.Firstname.Trim()) -FirstName $User.Firstname.Trim() -LastName $User.LastName.Trim() -Alias $User.alias.Trim() `
      -UserPrincipalName ($user.alias.Trim() +'@domain.loc') -RetentionPolicy MBSPolicy `
      -Password ( ConvertTo-SecureString $User.password.Trim() -AsPlainText -Force) -ResetPasswordOnNextLogon:$true `
      -ErrorVariable err | Out-Null
      Add-MailboxPermission -Identity $user.alias.Trim() -User "Mailbox Administrators" -AccessRights FullAccess -Automapping $false
    
#Map users home directory
    $Homedir = $User.Company
    Switch ($HomeDir)
	   {
        Test3 {$UserHomedir = "\\Test3-dataserv\staff\" + $User.alias; break}
	    Test2 {$UserHomedir = "\\Test2-dataserv\staff\" + $User.alias; break}
	    Test1 {$UserHomedir = "\\Test1-dataserv\staff\" + $User.alias; break}
	    Test6 {$UserHomedir = "\\Test6-dataserv\staff\" + $User.alias; break}
	    Test4 {$UserHomeDir = "\\Test4-dataserv\staff\" + $User.alias; break}
	    Test5 {$UserHomeDir = "\\Test5-dataserv\staff\" + $User.alias; break}
        }
#Check AD Latency
      do
      {
            $mailbox = Get-Mailbox -Identity $user.alias -ErrorAction SilentlyContinue
      }
      While ($mailbox -eq $null)

#Modify attributes of User's account properties
    $GetUser = (Get-ADUser -Identity $User.Alias).distinguishedName
       Set-ADUser $GetUser -Description $user.alias -City ($User.Alias + "@student.domain.k12.al.us") -Company $user.Company -Initials $user.Initials -HomeDrive G: -Title $user.Title -HomeDirectory ($UserHomedir + "\documents") `
      -Office $User.Company -PasswordNeverExpires:$false
       Add-Content $logfile -Value "<br>`n$($User.alias) account created.<br>" -encoding Utf8

#Move users to correct databases
   $MoveDatabase = $User.Database
    Switch ($MoveDatase)
    {
        {($User.Title -eq "Office")} {New-MoveRequest -Identity $User.Alias -TargetDatabase "MBS Office"; break}
        {($User.Title -eq "Staff")} {New-MoveRequest -Identity $User.Alias -TargetDatabase "MBS Staff 2"; break}
        {($User.Title -eq "Users")} {New-MoveRequest -Identity $User.Alias -TargetDatabase "MBS Staff 2"; break}
        }
#Add users to groups
    $AddGroup = $User.Title, $User.Company
    Switch ($AddGroup)
    {
        {($User.Title -eq "STAFF") -and ($User.Company -eq "Test3")} {Add-ADGroupMember -Identity "Test3 Staff" -Member $user.alias; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "Test3")} {Add-ADGroupMember -Identity "Test3 Office" -Member $user.alias; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "Test3")} {Add-ADGroupMember -Identity "Test3 Users" -Member $user.alias; break}
        {($User.Title -eq "STAFF") -and ($User.Company -eq "Test1")} {Add-ADGroupMember -Identity "Test1 Staff" -Member $user.alias; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "Test1")} {Add-ADGroupMember -Identity "Test1 Office" -Member $user.alias; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "Test1")} {Add-ADGroupMember -Identity "Test1 Users" -Member $user.alias; break}
        {($User.Title -eq "STAFF") -and ($User.Company -eq "Test2")} {Add-ADGroupMember -Identity "Test2 Staff" -Member $user.alias; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "Test2")} {Add-ADGroupMember -Identity "Test2 Office" -Member $user.alias; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "Test2")} {Add-ADGroupMember -Identity "Test2 Users" -Member $user.alias; break}
        {($User.Title -eq "STAFF") -and ($User.Company -eq "Test6")} {Add-ADGroupMember -Identity "Test6 Staff" -Member $user.alias; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "Test6")} {Add-ADGroupMember -Identity "Test6 Office" -Member $user.alias; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "Test6")} {Add-ADGroupMember -Identity "Test6 Users" -Member $user.alias; break}
        {($User.Title -eq "STAFF") -and ($User.Company -eq "Test4")} {Add-ADGroupMember -Identity "Test4 Staff" -Member $user.alias; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "Test4")} {Add-ADGroupMember -Identity "Test4 Office" -Member $user.alias; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "Test4")} {Add-ADGroupMember -Identity "Test4 Users" -Member $user.alias; break}
        {($User.Title -eq "STAFF") -and ($User.Company -eq "Test5")} {Add-ADGroupMember -Identity "Test5 Staff" -Member $user.alias; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "Test5")} {Add-ADGroupMember -Identity "Test5 Office" -Member $user.alias; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "Test5")} {Add-ADGroupMember -Identity "Test5 Users" -Member $user.alias; break}
        }


#Move users to correct OU.  
    $OUMove =  $User.Title, $User.Company
    Switch ($OUMove)
    {
        {($User.Title -eq "STAFF") -and ($User.Company -eq "Test3")} {Move-ADObject -Identity $GetUser -TargetPath $Test3STAFFOU; break}
        {($User.Title -eq "STAFF") -and ($User.Company -eq "Test1")} {Move-ADObject -Identity $GetUser -TargetPath $Test1STAFFOU; break}
        {($User.Title -eq "STAFF") -and ($User.Company -eq "Test2")} {Move-ADObject -Identity $GetUser -TargetPath $Test2STAFFOU; break}
        {($User.Title -eq "STAFF") -and ($User.Company -eq "Test6")} {Move-ADObject -Identity $GetUser -TargetPath $Test6STAFFOU; break}
        {($User.Title -eq "STAFF") -and ($User.Company -eq "Test5")} {Move-ADObject -Identity $GetUser -TargetPath $Test5STAFFOU; break}
        {($User.Title -eq "STAFF") -and ($User.Company -eq "Test4")} {Move-ADObject -Identity $GetUser -TargetPath $Test4StaffOU; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "Test3")} {Move-ADObject -Identity $GetUser -TargetPath $Test3USERSOU; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "Test1")} {Move-ADObject -Identity $GetUser -TargetPath $Test1USERSOU; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "Test2")} {Move-ADObject -Identity $GetUser -TargetPath $Test2USERSOU; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "Test5")} {Move-ADObject -Identity $GetUser -TargetPath $Test5USERSOU; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "Test4")} {Move-ADObject -Identity $GetUser -TargetPath $Test4USERSOU; break}
        {($User.Title -eq "USERS") -and ($User.Company -eq "Test6")} {Move-ADObject -Identity $GetUser -TargetPath $Test6USERSOU; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "Test3")} {Move-ADObject -Identity $GetUser -TargetPath $Test3OFFICEOU; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "Test1")} {Move-ADObject -Identity $GetUser -TargetPath $Test1OFFICEOU; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "Test2")} {Move-ADObject -Identity $GetUser -TargetPath $Test2OFFICEOU; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "Test6")} {Move-ADObject -Identity $GetUser -TargetPath $Test6OFFICEOU; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "Test5")} {Move-ADObject -Identity $GetUser -TargetPath $Test5OFFICOU; break}
        {($User.Title -eq "OFFICE") -and ($User.Company -eq "Test4")} {Move-ADObject -Identity $GetUser -TargetPath $Test4OFFICEOU; break}

    }
      }

#Add Home Directories


  if (!(Test-Path $Userhomedir)) {
    $homepath = ($Userhomedir + "\documents")
    New-Item $homepath -type directory 
    $acl = Get-Acl $Userhomedir
    $userval = $User.alias + "@domain.loc"
    $Acl.SetAccessRuleProtection($false, $True)
    $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($userval,'FullControl','ContainerInherit, ObjectInherit', 'None', 'Allow')
    $Acl.AddAccessRule($rule)
    $acl.SetAccessRule($accessRule)
    Set-Acl $Userhomedir $Acl
   }
} 

$body = Get-Content ("\\server1\c$\Temp\CreateStaff\staff.html") 
Send-mailMessage -From "admin@domain.k12.al.us" -To "admin2@domain.k12.al.us" -Subject "teacher account creation log" -Body ($body | Out-string) -bodyashtml:$true -smtpserver mail.domain.k12.al.us

Open in new window

0
 

Author Comment

by:falconcurt
ID: 40621385
New-MoveRequest : The call to 'net.tcp://server1.domain.loc/Microsoft.Exchange.MailboxReplicationService' failed because no
service was listening on the specified endpoint. Error details: Could not connect to
net.tcp://server1.domain.loc/Microsoft.Exchange.MailboxReplicationService. The connection attempt lasted for a time span of
00:00:02.0313316. TCP error code 10061: No connection could be made because the target machine actively refused it [::1]:808.
 --> No connection could be made because the target machine actively refused it [::1]:808
At C:\Temp\CreateStaff\Add-Mailbox.ps1:99 char:38
+         {($User.Title -eq "Staff")} {New-MoveRequest -Identity $User.Alias -Targ ...
+                                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [New-MoveRequest], EndpointNotFoundTransientException
    + FullyQualifiedErrorId : [Server=server1,RequestId=e215a5d1-10b7-4dad-b46f-ea7bca1c5e76,TimeStamp=2/20/2015 3:51:58 PM] [
   FailureCategory=Cmdlet-EndpointNotFoundTransientException] EBBA00A1,Microsoft.Exchange.Management.RecipientTasks.NewMoveR  
  equest
 
user3 does not exists creating account.
domain.loc/User... domain\Mailbox ... {FullAccess}                                                       False       False
Get-ADUser : Cannot find an object with identity: 'user3' under: 'DC=domain,DC=loc'.
At C:\Temp\CreateStaff\Add-Mailbox.ps1:89 char:17
+     $GetUser = (Get-ADUser -Identity $User.Alias).distinguishedName
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (user3:ADUser) [Get-ADUser], ADIdentityNotFoundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsof
   t.ActiveDirectory.Management.Commands.GetADUser
 
Set-ADUser : Directory object not found
At C:\Temp\CreateStaff\Add-Mailbox.ps1:90 char:8
+        Set-ADUser $GetUser -Description $user.alias -City ($User.Alias + "@stude ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (CN=user1\, MAR...domain,DC=loc:ADUser) [Set-ADUser], ADIdentityNotFoundExce
   ption
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsof
   t.ActiveDirectory.Management.Commands.SetADUser
 
New-MoveRequest : The call to 'net.tcp://server1.domain.loc/Microsoft.Exchange.MailboxReplicationService' failed because no
service was listening on the specified endpoint. Error details: Could not connect to
net.tcp://server1.domain.loc/Microsoft.Exchange.MailboxReplicationService. The connection attempt lasted for a time span of
00:00:02.0313371. TCP error code 10061: No connection could be made because the target machine actively refused it [::1]:808.
 --> No connection could be made because the target machine actively refused it [::1]:808
At C:\Temp\CreateStaff\Add-Mailbox.ps1:99 char:38
+         {($User.Title -eq "Staff")} {New-MoveRequest -Identity $User.Alias -Targ ...
+                                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [New-MoveRequest], EndpointNotFoundTransientException
    + FullyQualifiedErrorId : [Server=server1,RequestId=e215a5d1-10b7-4dad-b46f-ea7bca1c5e76,TimeStamp=2/20/2015 3:52:00 PM] [
   FailureCategory=Cmdlet-EndpointNotFoundTransientException] F8C63EC8,Microsoft.Exchange.Management.RecipientTasks.NewMoveR  
  equest
 
Move-ADObject : Directory object not found
At C:\Temp\CreateStaff\Add-Mailbox.ps1:136 char:70
+         {($User.Title -eq "STAFF") -and ($User.Company -eq "MBJH")} {Move-ADObje ...
+                                                                      ~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (CN=user1\, MAR...domain,DC=loc:ADObject) [Move-ADObject], ADIdentityNotFoun
   dException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsof
   t.ActiveDirectory.Management.Commands.MoveADObject
 
user2 does not exists creating account.
domain.loc/User... domain\Mailbox ... {FullAccess}                                                       False       False
Get-ADUser : Cannot find an object with identity: 'user2' under: 'DC=domain,DC=loc'.
At C:\Temp\CreateStaff\Add-Mailbox.ps1:89 char:17
+     $GetUser = (Get-ADUser -Identity $User.Alias).distinguishedName
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (user2:ADUser) [Get-ADUser], ADIdentityNotFoundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsof
   t.ActiveDirectory.Management.Commands.GetADUser
 
Set-ADUser : Directory object not found
At C:\Temp\CreateStaff\Add-Mailbox.ps1:90 char:8
+        Set-ADUser $GetUser -Description $user.alias -City ($User.Alias + "@stude ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (CN=user1\, MAR...domain,DC=loc:ADUser) [Set-ADUser], ADIdentityNotFoundExce
   ption
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsof
   t.ActiveDirectory.Management.Commands.SetADUser
 
New-MoveRequest : The call to 'net.tcp://server1.domain.loc/Microsoft.Exchange.MailboxReplicationService' failed because no
service was listening on the specified endpoint. Error details: Could not connect to
net.tcp://server1.domain.loc/Microsoft.Exchange.MailboxReplicationService. The connection attempt lasted for a time span of
00:00:02.0157020. TCP error code 10061: No connection could be made because the target machine actively refused it [::1]:808.
 --> No connection could be made because the target machine actively refused it [::1]:808
At C:\Temp\CreateStaff\Add-Mailbox.ps1:99 char:38
+         {($User.Title -eq "Staff")} {New-MoveRequest -Identity $User.Alias -Targ ...
+                                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [New-MoveRequest], EndpointNotFoundTransientException
    + FullyQualifiedErrorId : [Server=server1,RequestId=e215a5d1-10b7-4dad-b46f-ea7bca1c5e76,TimeStamp=2/20/2015 3:52:04 PM] [
   FailureCategory=Cmdlet-EndpointNotFoundTransientException] 211751E9,Microsoft.Exchange.Management.RecipientTasks.NewMoveR  
  equest
 
Move-ADObject : Directory object not found
At C:\Temp\CreateStaff\Add-Mailbox.ps1:131 char:69
+         {($User.Title -eq "STAFF") -and ($User.Company -eq "Test1")} {Move-ADObjec ...
+                                                                     ~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (CN=user1\, MAR...domain,DC=loc:ADObject) [Move-ADObject], ADIdentityNotFoun
   dException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsof
   t.ActiveDirectory.Management.Commands.MoveADObject
0
 

Author Comment

by:falconcurt
ID: 40621500
Ok. I have an update. I changed line 90 from
Set-ADUser $GetUser -Description $user.alias to
$GetUser | Set-Aduser -Description $user.alias which removed some of those errors.

The third user in the CSV file doesn't work correctly. It creates the user but it doesn't change the properties of the user or move him to the correct OU. It comes up with the following message. It actually states user2 user in the error message when it tries to create the user1.

Get-ADUser : Cannot find an object with identity: 'USER2' under: 'DC=domain,DC=loc'.
At C:\Temp\CreateStaff\Add-Mailbox.ps1:89 char:17
+     $GetUser = (Get-ADUser -Identity $User.Alias).distinguishedName
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (USER2:ADUser) [Get-ADUser], ADIdentityNotFoundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsof
   t.ActiveDirectory.Management.Commands.GetADUser
 
Set-ADUser : Directory object not found
At C:\Temp\CreateStaff\Add-Mailbox.ps1:90 char:19
+        $GetUser | Set-ADUser -Description $user.alias -City ($User.Alias + "@stu ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (CN=USER1\, EMIL...domain,DC=loc:ADUser) [Set-ADUser], ADIdentityNotFoundExce
   ption
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsof
   t.ActiveDirectory.Management.Commands.SetADUser
 
New-MoveRequest : The call to 'net.tcp://server1.domain.loc/Microsoft.Exchange.MailboxReplicationService' failed because no
service was listening on the specified endpoint. Error details: Could not connect to
net.tcp://server1.domain.loc/Microsoft.Exchange.MailboxReplicationService. The connection attempt lasted for a time span of
00:00:02.0157071. TCP error code 10061: No connection could be made because the target machine actively refused it [::1]:808.
 --> No connection could be made because the target machine actively refused it [::1]:808
At C:\Temp\CreateStaff\Add-Mailbox.ps1:99 char:38
+         {($User.Title -eq "Staff")} {New-MoveRequest -Identity $User.Alias -Targ ...
+                                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [New-MoveRequest], EndpointNotFoundTransientException
    + FullyQualifiedErrorId : [Server=server1,RequestId=e215a5d1-10b7-4dad-b46f-ea7bca1c5e76,TimeStamp=2/20/2015 4:25:52 PM] [
   FailureCategory=Cmdlet-EndpointNotFoundTransientException] 3BC8D901,Microsoft.Exchange.Management.RecipientTasks.NewMoveR  
  equest
 
Move-ADObject : Directory object not found
At C:\Temp\CreateStaff\Add-Mailbox.ps1:131 char:69
+         {($User.Title -eq "STAFF") -and ($User.Company -eq "MBE")} {Move-ADObjec ...
+                                                                     ~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (CN=USER1\, EMIL...domain,DC=loc:ADObject) [Move-ADObject], ADIdentityNotFoun
   dException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsof
   t.ActiveDirectory.Management.Commands.MoveADObject
 


 
 
I seem to have a big problem with the New-MoveRequest command. This error happens
New-MoveRequest : The call to 'net.tcp://mbcas1.mtnbrook.loc/Microsoft.Exchange.MailboxReplicationService' failed because no
service was listening on the specified endpoint. Error details: Could not connect to
net.tcp://mbcas1.mtnbrook.loc/Microsoft.Exchange.MailboxReplicationService. The connection attempt lasted for a time span of
00:00:02.0157071. TCP error code 10061: No connection could be made because the target machine actively refused it [::1]:808.
 --> No connection could be made because the target machine actively refused it [::1]:808
At C:\Temp\CreateStaff\Add-Mailbox.ps1:99 char:38
+         {($User.Title -eq "Staff")} {New-MoveRequest -Identity $User.Alias -Targ ...
+                                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [New-MoveRequest], EndpointNotFoundTransientException
    + FullyQualifiedErrorId : [Server=MBCAS1,RequestId=e215a5d1-10b7-4dad-b46f-ea7bca1c5e76,TimeStamp=2/20/2015 4:25:52 PM] [
   FailureCategory=Cmdlet-EndpointNotFoundTransientException] 3BC8D901,Microsoft.Exchange.Management.RecipientTasks.NewMoveR  
  equest
0
 
LVL 39

Expert Comment

by:footech
ID: 40622409
I think you need to add some error checking after some of the operations before moving on.  That is likely why your last change cut down on some errors.  If $GetUser is blank, then piping it to Set-ADUser won't do anything, but calling Set-ADUser with a blank identity will raise an error.  If I remember right, here's another scenario that can occur:
Say, the first time through the loop $user is successfully processed, and $GetUser = (Get-ADUser -Identity $User.Alias).distinguishedName encounters no error, so $GetUser has a value (I'll just call it value1).  The rest of the script proceeds working with value1  Then, the next time through the loop, when running the same command there is an error, and what happens is that $GetUser isn't updated, instead of being value2, it is still value1, and the rest of the script proceeds working with value1 when that's not what you want.
Here's one way to check for the error:
    #Modify attributes of User's account properties
        try {
            $GetUser = (Get-ADUser -Identity $User.Alias).distinguishedName -errorAction Stop
        } Catch {
            Write-Output "Error encountered - $($_.exception.message)"
            Write-Output "Exiting script..."
            exit
        }
        Set-ADUser $GetUser -Description $user.alias -City ($User.Alias + "@student.domain.k12.al.us") -Company $user.Company -Initials $user.Initials -HomeDrive G: -Title $user.Title -HomeDirectory ($UserHomedir + "\documents") `
          -Office $User.Company -PasswordNeverExpires:$false

Open in new window


The variable name in Line 96 was misspelled, but I think there's a bigger problem with your switch statements.  The code may actually work, but employing the switch syntax there doesn't add anything and makes it harder to read.  For example, you use Switch ($MoveDatabase) (variable name corrected), but the value of $MoveDatabase is completely irrelevant to the rest of the switch statement.  I'd suggest that it's better to use If/ElseIf checks here.  However, with the switch syntax the following would also appear correct.
Switch ($User.Title)
        {
            "Office" {New-MoveRequest -Identity $User.Alias -TargetDatabase "MBS Office"; break}
            "Staff" {New-MoveRequest -Identity $User.Alias -TargetDatabase "MBS Staff 2"; break}
            "Users" {New-MoveRequest -Identity $User.Alias -TargetDatabase "MBS Staff 2"; break}
         }

Open in new window

But maybe if you actually want to use the value of $user.database...
0
 

Author Comment

by:falconcurt
ID: 40623258
I get this error when running the get-aduser with the -errorAction

+                                                                             ~~~~
Unexpected token '-ErrorAction' in expression or statement.
At C:\Temp\CreateStaff\Add-Mailbox.ps1:90 char:90
+ ... e -ErrorAction Stop
+                    ~~~~
Unexpected token 'Stop' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken
0
 
LVL 39

Expert Comment

by:footech
ID: 40623309
Sorry, the parameter needs to be inside the parentheses.
$GetUser = (Get-ADUser -Identity $User.Alias -errorAction Stop).distinguishedName

Open in new window

0
Don't lose your head updating email signatures!

Do your end users still have the wrong email signature? Do email signature updates bore you or fill you with a sense of dread? You can make this a whole lot easier on yourself by trusting an Exclaimer email signature management solution. Over 50 million users do...so should you!

 

Author Comment

by:falconcurt
ID: 40623481
Well, it definitely stops at the second user attempting to get-aduser. The thing it does exists. I can do a search in Active Directory and i can locate user2.  It comes up with this message

user2 does not exists creating account.
domain.loc/User... Domain\Mailbox ... {FullAccess}                                                       False       False
Error encountered - Cannot find an object with identity: 'user2' under: 'DC=domain,DC=loc'.
Exiting script...
0
 
LVL 39

Expert Comment

by:footech
ID: 40623505
I'm curious why you have the Check-ADUser function which uses ADSI, and then later use the AD cmdlet Get-ADUser.

I notice that in the function you split the alias at "\".  Why don't you do the same for Get-ADUser?

Have you checked that the created user has a samaccountname attribute?  You probably need to add that to the New-Mailbox command.  The -Identity parameter for Get-ADUser takes a distinguishedname, GUID, SID, samaccountname, or name, and it looks like you're trying to use the alias as the samaccountname.
0
 

Author Comment

by:falconcurt
ID: 40624978
There is no specific reason.. I am still a noob and learning Powershell. The user has a samAccountName in the AD attributes.
0
 
LVL 39

Expert Comment

by:footech
ID: 40625001
Maybe a timing issue?
After the script fails, try just running a Get-ADUser command manually (after a few seconds, and then after a few minutes) and see if you can retrieve the user that it says it couldn't find.
0
 

Author Comment

by:falconcurt
ID: 40625005
I just ran  the Get-ADUser right after the script completed and it found user2. I say about 1-2 seconds
0
 
LVL 39

Accepted Solution

by:
footech earned 500 total points
ID: 40625028
Then I would just put a Start-Sleep command in there to delay the check, and adjust the time till you're not getting the error.
0
 

Author Comment

by:falconcurt
ID: 40634637
That pretty much did it footech. I placed the Start-sleep command after the new-mailbox command and all users got created. The new-moverequest still doesnt work but i believe that is another problem.  I am about to ask the question in the Exchange category. Thanks
0

Featured Post

Promote certifications in your email signature

Has your company recently won an award or achieved a certification? They'll no doubt want to show it off. Email signature images used to promote certifications & awards can instantly establish credibility with a recipient and provide you with numerous benefits.

Join & Write a Comment

Disabling the Directory Sync Service Account in Office 365 will stop directory synchronization from working.
This article will help you understand what HashTables are and how to use them in PowerShell.
In this video we show how to create a Distribution Group in Exchange 2013. We show this process by using the Exchange Admin Center. Log into Exchange Admin Center.: First we need to log into the Exchange Admin Center. Navigate to the Recipients >>…
how to add IIS SMTP to handle application/Scanner relays into office 365.

706 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now