Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 401
  • Last Modified:

Editing Active Directory user with powershell

I am trying to edit my powershell script to edit Active Directory users that have been identified by the Distinguished name in AD. I added an if statement that tries to look at a csv field and if its in an arrary do this. It is skipping to the else statement at this statement

 If ($User.Grade -contains $Grade78Array)
        {Set-QADUser -Identity ("CN=" + $User.LastName + "\"", " + $User.Firstname + $DNUser78)  

I believe i got the syntax wrong here somewhere in the If statement. here is my script.
add-PSSnapin Quest.ActiveRoles.ADManagement 
Import-Module ActiveDirectory

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 C:\Temp\xxxxAD.csv
$xxxxHomePath = "\\xxxx-dataserv\students\"
$78 = "xxxxxxxx.loc/District Schools/xxxx/School Users/Student/7-8"
$9 = "xxxxxxxx.loc/District Schools/xxxx/School Users/Student/9"
$Grade78Array = "7","8"
$Grade9Array = "9"
$DNUser78 = ",OU=7-8,OU=Student,OU=School Users,OU=xxxx,OU=District Schools,DC=xxxxxxxx,DC=loc"
$DNUser9 = ",OU=9,OU=Student,OU=School Users,OU=xxxx,OU=District Schools,DC=xxxxxxxx,DC=loc"
$logfile = "c:\Temp\xxxxstudents.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.Username).Status
    If ($Status -eq 1)
    {
        write-host "$($User.Username) exists modifying attributes" 
        "$($User.username) exists modifying attributes." | Add-Content $logfile
	 If ($User.Grade -contains $Grade78Array)
        {Set-QADUser -Identity ("CN=" + $User.LastName + "\"", " + $User.Firstname + $DNUser78) `
	    -Email ($user.Username +"@student.xxxxxxxx.xxx.xx.xx") `
	    -DisplayName $user.displayname `
	    -Description $user.Username `
	    -Initials $user.Initial `
	    -Firstname $user.Firstname `
	    -Lastname $user.Lastname `
        -PostOfficeBox $user.StudentID `
        -UserPassword $user.password `
 } Else {
        Set-QADUser -Identity ("CN=" + $User.LastName + "\"", " + $User.Firstname + $DNUser9) `
	    -Email ($user.Username +"@xxxxxx@xxxxxxxx") `
	    -DisplayName $user.displayname `
	    -Description $user.Username `
	    -Initials $user.Initial `
	    -Firstname $user.Firstname `
	    -Lastname $user.Lastname `
        -PostOfficeBox $user.StudentID `
        -UserPassword $user.password `
    } Else {
        Write-Host "$($User.username) does not exists creating account." -ForegroundColor Yellow
        "$($User.username) does not exists creating account." | add-content $logfile
    #Modify attributes of Users account properties
        New-QADUser -Name ($User.LastName + ", " + $User.Firstname) `
        -ParentContainer "OU=Student,OU=School Users,OU=xxxx,OU=District Schools,DC=xxxxxxxx,DC=loc" `
        -Description $user.Username `
        -Company "xxxx" `
        -Initials $user.Initial `
        -SamAccountName $User.Username `
        -Title "Students" `
        -DisplayName ($User.LastName + ", " + $User.Firstname) `
        -FirstName $user.Firstname `
        -LastName $user.Lastname `
        -HomeDirectory ($xxxxHomePath + $User.Username + "\documents")`
        -Office "xxxx" `
        -PostOfficeBox $user.StudentID `
        -l ($user.Username + "@student.xxxxxxxx.xxx.xx.xx") `
        -Email ($user.Username +"@student.xxxxxxxx.xxx.xx.xx") `
        -UserPassword $user.password `
        -UserPrincipalName ($user.Username +"@xxxxxxxx.loc") `
        -HomeDrive "G" | Set-QADUSER -PasswordNeverExpires:$true
        Add-QADPermission -Identity $user.Username -Account SELF,Everyone -Extendedright "User-Change-Password" -Deny -ApplyTo ThisObjectOnly
        Add-ADGroupMember -Identity "xxxx Students" -Member $user.Username
        Add-Content $logfile -Value "`n$($User.username) account created." -encoding Utf8
    }

}
    #Moves   
    $OUMove =  $User.Grade
    Switch ($OUMove)
    {
        7 {Move-QADObject $User.Username -NewParentContainer $78}
        8 {Move-QADObject $User.Username -NewParentContainer $78}
        9 {Move-QADObject $User.Username -NewParentContainer $9}
    }
    $homedir = ($xxxxHomePath + $User.Username)
    if (!(test-Path $homedir)) {
        $homepath = ($homedir + "\documents")
        New-Item $homepath -type directory 
        $acl = Get-Acl $homedir
        $userval = $User.Username + "@xxxxxxxx.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 $homedir $Acl
    }

}
$body = Get-Content ("C:\Temp\xxxxstudents.csv") 
Send-mailMessage -From "admin@xxxxxxxx.xxx.xx.xx" -To "xxxxxxx@xxxxxxxx.xxx.xx.xx" -Subject "Student account creation log" -Attachments "C:\Temp\xxxxstudents.csv" -smtpserver mail.xxxxxxxx.xxx.xx.xx

Open in new window

0
falconcurt
Asked:
falconcurt
  • 6
  • 5
1 Solution
 
SubsunCommented:
I guess $User.Grade value is not an array.. So, What if you try  
If ($Grade78Array -contains $User.Grade )

Open in new window

0
 
footechCommented:
You just need to reverse the order.
If ($Grade78Array -contains $User.Grade)

Open in new window


Edit:  Subsun - you beat me to it!
0
 
SubsunCommented:
Another error I could find is in your if else statement. You missed to add the second condition..
If ($User.Grade -contains $Grade78Array)
        {Set-QADUser -Identity ("CN=" + $User.LastName + "\"", " + $User.Firstname + $DNUser78) `
	    #
 } Elseif (<Add second condition here>) {
        Set-QADUser -Identity ("CN=" + $User.LastName + "\"", " + $User.Firstname + $DNUser9) `
	    #Rest of the code
 } Else {
   #If both the above conditions wont match then execute following..
     Write-Host "$($User.username) does not exists creating account." -ForegroundColor Yellow
    #Rest of the code
 }

Open in new window

@footech, Just had a super coffee... ;-)
0
Simplify Active Directory Administration

Administration of Active Directory does not have to be hard.  Too often what should be a simple task is made more difficult than it needs to be.The solution?  Hyena from SystemTools Software.  With ease-of-use as well as powerful importing and bulk updating capabilities.

 
falconcurtAuthor Commented:
Does that fit with this complete statement. It is giving me weird results.
Foreach ($User in $Users){

    #check if the user exists
    $Status = (Check-ADUser -username $User.Username).Status
    If ($Status -eq 1)
    {
        write-host "$($User.Username) exists modifying attributes" 
        "$($User.username) exists modifying attributes." | Add-Content $logfile
	 If ($Grade78Array -contains $User.Grade)
        #edit account properties
        {Set-QADUser -Identity ("CN=" + $User.LastName + "\"", " + $User.Firstname + $DNUser78) `
	    -Email ($user.Username +"@student.xxxxxx.xxx.xx.xx") `
	    -DisplayName $user.displayname `
	    -Description $user.Username `
	    -Initials $user.Initial `
	    -Firstname $user.Firstname `
	    -Lastname $user.Lastname `
        -PostOfficeBox $user.StudentID `
        -UserPassword $user.password `
 } Elseif ($Grade9Arrary -contains $User.Grade) {
        Set-QADUser -Identity ("CN=" + $User.LastName + "\"", " + $User.Firstname + $DNUser9) `
	    -Email ($user.Username +"@student.xxxxxx.xxx.xx.xx") `
	    -DisplayName $user.displayname `
	    -Description $user.Username `
	    -Initials $user.Initial `
	    -Firstname $user.Firstname `
	    -Lastname $user.Lastname `
        -PostOfficeBox $user.StudentID `
        -UserPassword $user.password `
    } Else {
        Write-Host "$($User.username) does not exists creating account." -ForegroundColor Yellow
        "$($User.username) does not exists creating account." | add-content $logfile
    #Create new account
        New-QADUser -Name ($User.LastName + ", " + $User.Firstname) `
        -ParentContainer "OU=Student,OU=School Users,OU=xxxx,OU=District Schools,DC=xxxxxxx,DC=loc" `
        -Description $user.Username `
        -Company "xxxx" `
        -Initials $user.Initial `
        -SamAccountName $User.Username `
        -Title "Students" `
        -DisplayName ($User.LastName + ", " + $User.Firstname) `
        -FirstName $user.Firstname `
        -LastName $user.Lastname `
        -HomeDirectory ($xxxxHomePath + $User.Username + "\documents")`
        -Office "xxxx" `
        -PostOfficeBox $user.StudentID `
        -l ($user.Username + "@student.xxxxxx.xxx.xx.xx") `
        -Email ($user.Username +"@student.xxxxxx.xxx.xx.xx") `
        -UserPassword $user.password `
        -UserPrincipalName ($user.Username +"@xxxxxxx.loc") `
        -HomeDrive "G" | Set-QADUSER -PasswordNeverExpires:$true
        Add-QADPermission -Identity $user.Username -Account SELF,Everyone -Extendedright "User-Change-Password" -Deny -ApplyTo ThisObjectOnly
        Add-ADGroupMember -Identity "xxxx Students" -Member $user.Username
        Add-Content $logfile -Value "`n$($User.username) account created." -encoding Utf8
    }

}
    #Moves   
    $OUMove =  $User.Grade
    Switch ($OUMove)
    {
        7 {Move-QADObject $User.Username -NewParentContainer $78}
        8 {Move-QADObject $User.Username -NewParentContainer $78}
        9 {Move-QADObject $User.Username -NewParentContainer $9}
    }
    $homedir = ($xxxxHomePath + $User.Username)
    if (!(test-Path $homedir)) {
        $homepath = ($homedir + "\documents")
        New-Item $homepath -type directory 
        $acl = Get-Acl $homedir
        $userval = $User.Username + "@xxxxxxx.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 $homedir $Acl
    }

}

Open in new window

0
 
SubsunCommented:
It is giving me weird results.
Can you explain?

You also remove the tick marks at the end of Line 19 & 29
Untitled.pngShould be like
--------------------------
        -PostOfficeBox $user.StudentID `
        -UserPassword $user.password
    } Else {
--------------

Open in new window

0
 
falconcurtAuthor Commented:
I should have edited that... It's telling me it's modifying attributes then it skips to User doesn't exist creating user. Then errors informing me account already exists.
0
 
SubsunCommented:
Ok.. can you post a sample of input csv file? you may remove the confidential information before posting..

Also check if your Check-ADUser function return expected result..
0
 
falconcurtAuthor Commented:
Sorry Sub, i entered an extra parenthesis where it didn't belong. I fix that but i do however get this message

Cannot convert value "testuser" to type "System.Int32". Error: "Input string was not in a correct format."
At C:\Temp\xxxxxstudents.ps1:52 char:9
+         Set-QADUser -Identity [string]("CN=" + $User.LastName + "\", + $User.Fir ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastFromStringToInteger


This is line 52 -
  Set-QADUser -Identity ("CN=" + $User.LastName + "\", + $User.Firstname + $DNUser78) `
0
 
SubsunCommented:
First make sure the following constructs the actual DN of the user?  Compare it with actual user in AD, probably it may not be matching as expected.
("CN=" + $User.LastName + "\", + $User.Firstname + $DNUser78)

Cannot convert value "testuser" to type "System.Int32"
The error shows the script trying to convert a String to INT. I don't see anything related to it in your code from above post..  Probably you can post the updated code and we can verify it..
0
 
falconcurtAuthor Commented:
Here is the full code
add-PSSnapin Quest.ActiveRoles.ADManagement 
Import-Module ActiveDirectory

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 C:\Temp\xxxxAD.csv
$xxxxHomePath = "\\xxxx-dataserv\students\"
$78 = "xxxxxx.loc/District Schools/xxxx/School Users/Student/7-8"
$9 = "xxxxxx.loc/District Schools/xxxx/School Users/Student/9"
$Grade78Array = "7","8"
$Grade9Array = "9"
[string]$DNUser78 = ",OU=7-8,OU=Student,OU=School Users,OU=xxxx,OU=District Schools,DC=xxxxxx,DC=loc"
[string]$DNUser9 = ",OU=9,OU=Student,OU=School Users,OU=xxxx,OU=District Schools,DC=xxxxxx,DC=loc"
$logfile = "c:\Temp\xxxxstudents.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.Username).Status
    If ($Status -eq 1)
   {
        write-host "$($User.Username) exists modifying attributes" 
        "$($User.username) exists modifying attributes." | Add-Content $logfile
	} if ($Grade78Array -contains $User.Grade) {
        Set-QADUser -Identity ("CN=" + $User.LastName + "\", + $User.Firstname + $DNUser78) `
	    -Email ($user.Username +"@student.xxxxxx.xxx.xx.xx") `
	    -DisplayName $user.displayname `
	    -Description $user.Username `
	    -Initials $user.Initial `
	    -Firstname $user.Firstname `
	    -Lastname $user.Lastname `
        -PostOfficeBox $user.StudentID `
        -UserPassword $user.password
        
 } Elseif ($Grade9Arrary -contains $User.Grade){
         Set-QADUser -Identity ("CN=" + $User.LastName + "\", + $User.Firstname + $DNUser9) `
        -Email ($user.Username +"@student.xxxxxx.xxx.xx.xx") `
	    -DisplayName $user.displayname `
	    -Description $user.Username `
	    -Initials $user.Initial `
	    -Firstname $user.Firstname `
	    -Lastname $user.Lastname `
        -PostOfficeBox $user.StudentID `
        -UserPassword $user.password 
    }
    
   Else {
        Write-Host "$($User.username) does not exists creating account." -ForegroundColor Yellow
        "$($User.username) does not exists creating account." | add-content $logfile
    #Create new account
        New-QADUser -Name ($User.LastName + ", " + $User.Firstname) `
        -ParentContainer "OU=Student,OU=School Users,OU=xxxx,OU=District Schools,DC=xxxxxx,DC=loc" `
        -Description $user.Username `
        -Company "xxxx" `
        -Initials $user.Initial `
        -SamAccountName $User.Username `
        -Title "Students" `
        -DisplayName ($User.LastName + ", " + $User.Firstname) `
        -FirstName $user.Firstname `
        -LastName $user.Lastname `
        -HomeDirectory ($xxxxHomePath + $User.Username + "\documents")`
        -Office "xxxx" `
        -PostOfficeBox $user.StudentID `
        -l ($user.Username + "@student.xxxxxx.xxx.xx.xx") `
        -Email ($user.Username +"@student.xxxxxx.xxx.xx.xx") `
        -UserPassword $user.password `
        -UserPrincipalName ($user.Username +"@xxxxxx.loc") `
        -HomeDrive "G" | Set-QADUSER -PasswordNeverExpires:$true
        Add-QADPermission -Identity $user.Username -Account SELF,Everyone -Extendedright "User-Change-Password" -Deny -ApplyTo ThisObjectOnly
        Add-ADGroupMember -Identity "xxxx Students" -Member $user.Username
        Add-Content $logfile -Value "`n$($User.username) account created." -encoding Utf8
    }

    #Moves   
    $OUMove =  $User.Grade
    Switch ($OUMove)
    {
        7 {Move-QADObject $User.Username -NewParentContainer $78}
        8 {Move-QADObject $User.Username -NewParentContainer $78}
        9 {Move-QADObject $User.Username -NewParentContainer $9}
    }
    $homedir = ($xxxxHomePath + $User.Username)
    if (!(test-Path $homedir)) {
        $homepath = ($homedir + "\documents")
        New-Item $homepath -type directory 
        $acl = Get-Acl $homedir
        $userval = $User.Username + "@xxxxxx.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 $homedir $Acl
    }
}

$body = Get-Content ("C:\Temp\xxxxstudents.csv") 
Send-mailMessage -From "admin@xxxxxx.xxx.xx.xx" -To "xxxxxxxx@xxxxxx.xxx.xx.xx" -Subject "Student account creation log" -Attachments "C:\Temp\xxxxstudents.csv" -smtpserver mail.xxxxxx.xxx.xx.xx

Open in new window

0
 
falconcurtAuthor Commented:
I got sub, you were right regarding the matching of the Distinguished Name. Once i got the comma and space corrected in the code it worked. Much appreciated.

from
("CN=" + $User.LastName + "\", + $User.Firstname + $DNUser9)
to
("CN=" + $User.LastName + "\" + ", " + $User.Firstname + $DNUser78)
0
 
falconcurtAuthor Commented:
Great work Subsun and very patient for a novice scripter :)
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 6
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now