Jump to content

Recommended Posts

Posted

Create Users, Add to Groups, Move to OU, Create Folder, Set ACL, Create Share.

 

Early version, will almost certainly have bugs - for interest only.

 

# ===========================================================================
# Script : CreateUserFromCSV.ps1
# Author : PCS
# Created: July 2013
# Notes  : Create AD Users from CSV file
#          Add User to appropriate groups
#          Move the User to an appropriate OU, 
#          Create appropriate folder on file server, 
#          Set ACL Permissions on folder
#
#          CSV should contain : Prefix, UserName, StudentId, Password
#
#          Produces a log file as a CSV
#
# ===========================================================================

# Globals
$DomEmail="@thedomain.org.uk"
$DomBase="DC=thedomain, DC=org, DC=uk"
$HomeBase="\\server\F\Students\"
$ServBase="F:\Students\"
$NTDomain="THEDOMAIN"

$InFile = "c:\Users\userlist.csv"
$LogFile = "c:\CreateLog.csv"


Import-Module ActiveDirectory

# ---------------------------------------------------------------------------
# Function : AddStudentUser
# Notes    : Check if a user account already exists. If not, create the 
#            account
#
# ---------------------------------------------------------------------------
function AddStudentUser  {

   Param ([string]$UserName, [string]$Password, [string]$StudentId )

   # Set the other stuff we need
   $defpassword = (ConvertTo-SecureString "$Password" -AsPlainText -force)
   $UserEmail = $UserName + $DomEmail
   
   # Can we find a User with this SAMAccountName?
Get-ADUser $UserName -errorvariable $iserror | out-null
if($?){
       # User Already Exists, Set a meaningful return Value
       $AddStudentUser = "$UserName Already Exists" 
   } else {
       
       # Create the Users AD Account 
       try {
               New-ADUser $UserName -SamAccountName $UserName -EmailAddress ($UserEMail) `
                                    -UserPrincipalName ($UserEmail) `
                                    -AccountPassword ($defpassword) -EmployeeID ($StudentId) `
                                    -Enabled $true -ChangePasswordAtLogon $false `
                                    -ScriptPath "sclogon.bat" -homeDrive "N:" -HomeDirectory "\\Server\$UserName$"                                     
               
               $AddStudentUser = "$UserName Created"                                                
           }
       catch [system.Object] {
           Write-Host "Error Creating User : $UserName "
               
       }        
   }

   $AddStudentUser

} 
# End function AddStudentUser 
# ---------------------------------------------------------------------------


# ---------------------------------------------------------------------------
# Function : AddGroupsForStudent
# Notes    : Add Account to Group
# ---------------------------------------------------------------------------
function AddGroupsForStudent {
   
   Param ([string]$UserName, [string]$Group )
   
   try {
      # Add to Appropriate Groups 
      Add-ADGroupMember -Identity $Group -Member $UserName                
      $AddGroupsForStudent = "OK"
} catch [system.Object] {
      $AddGroupsForStudent = "Error"    
   }        

   $AddGroupsForStudent    

}
# End function AddStudentUser 
# ---------------------------------------------------------------------------


# ---------------------------------------------------------------------------
# Function : MoveStudentUser
# Notes    : Move a given student user to the correct OU
# ---------------------------------------------------------------------------
function MoveStudentUser {

   Param ([string]$UserName, [string]$TargetOU )

   try {
   Get-ADUser $UserName | Move-ADObject -TargetPath "$TargetOU, $DomBase"
      $MoveStudentUser = "Moved"
} catch [system.Object] {
      $MoveStudentUser = "Error Moving to $TargetOU"
   }        
   
   $MoveStudentUser    

}
# End function MoveStudentUser
# ---------------------------------------------------------------------------



# ---------------------------------------------------------------------------
#
#
# ---------------------------------------------------------------------------
function CreateStudentFolder {

   Param ([string]$UserName, [string]$Target )
   
   $tdir = $HomeBase + $UserName
   
   # Check folder exist and if not, create.
   if (!(Test-Path $tdir)) {
       New-Item $tdir -type DIRECTORY
       $CreateStudentFolder="$tdir Folder Created"
   } else {
       $CreateStudentFolder="$tdir Folder Already Exists"        
   }    
   
   $CreateStudentFolder
   
}
# End function CreateStudentFolder
# ---------------------------------------------------------------------------




# ---------------------------------------------------------------------------
# CreateStudentShare
#
# ---------------------------------------------------------------------------
function CreateStudentShare {

   Param ([string]$UserName )
       
   $tdir = $ServBase + $UserName
   $Sharename = "$UserName`$"
   Write-Host $Sharename
   $CreateStudentShare="No value"
   
$Shares = [WMICLASS] "\\\Root\Cimv2:Win32_Share"
   Write-Host "WMI Done"

   try {
      $result=$Shares.Create($tdir,$Sharename,0)
      Write-Host $result.returnvalue
      $CreateStudentShare="$Sharename Created"
      Write-Host "WMI 3"
   } catch [system.Object] {
      $CreateStudentShare="Error Creating Share : $Sharename for $tdir"
   }
   
   $CreateStudentShare
   
}
# End function CreateStudentShare
# ---------------------------------------------------------------------------




# ---------------------------------------------------------------------------
# SetFolderACL
#
# ---------------------------------------------------------------------------
function SetFolderACL {

   Param ([string]$UserName )
   
   $SetFolderACL = "No Work Done"
   $tdir = $HomeBase + $UserName
   Write-Host $tdir
   
   try {
       $acl = Get-Acl $tdir
       $acl.SetAccessRuleProtection($True, $False)
       $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("Everyone","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
       $acl.RemoveAccessRuleAll($rule)
       $rule = New-Object System.Security.AccessControl.FileSystemAccessRule("Administrators","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
       $acl.AddAccessRule($rule)
       $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($UserName,"Modify", "ContainerInherit, ObjectInherit", "None", "Allow")
       $acl.AddAccessRule($rule)
       $acct=New-Object System.Security.Principal.NTAccount($NTDomain,$UserName)
       $acl.SetOwner($acct)
       Set-Acl $tdir $acl
       $SetFolderACL = "$tdir ACL set OK"
} catch [system.Object] {
      $SetFolderACL = "Error setting $tdir ACL"
   }        

   $SetFolderACL

}
# ---------------------------------------------------------------------------







# ===========================================================================
# MAIN
# ===========================================================================

$AccList=Import-CSV $InFile

# Obj stuff is for producing a log
$ObjArr = @()
$ObjIdx = 0


foreach ($acc in $accList) {

   # Concatenate for the Username
   $UserName = $(($acc.Prefix)+$($acc.UserName))

   $Obj = New-Object System.object
   $Obj | Add-Member –Type NoteProperty –name UserName -value $UserName

   # Create The User
   $CreatedStatus=AddStudentUser $($UserName) $($acc.Password) $($acc.StudentId)
   $Obj | Add-Member –Type NoteProperty –name CreatedStatus -value $($CreatedStatus)
   
   # Move to appropriate OU
   $MoveStatus=MoveStudentUser $UserName "OU=Pre16"
   $Obj | Add-Member –Type NoteProperty –name OUMoveStatus -value $MoveStatus

   # Create the Users Folder
   $FolderStatus=CreateStudentFolder $UserName
   $Obj | Add-Member –Type NoteProperty –name FolderStatus -value $FolderStatus

   $ShareStatus = CreateStudentShare $UserName
   $Obj | Add-Member –Type NoteProperty –name ShareStatus -value $($ShareStatus)

   $ACLStatus=SetFolderACL $UserName
   $Obj | Add-Member –Type NoteProperty –name ACLStatus -value $($ACLStatus)
   

   $ObjArr += $Obj    
   $ObjIdx ++
   
}

# Write the log file
$ObjArr | Export-CSV $LogFile -notype

# ===========================================================================
# THE END
# ===========================================================================


  • Thanks 1
  • 5 weeks later...
Posted
Well, it worked for me! You will need to test it for your own particular set-up. If you have problems, shout and I'll try and help. I'll also put out an update next week which will make multiple groups easier to deal with and will handle email enabling of the asccounts on an exchange server.
Posted (edited)
How does it know what OU or Group to put the user in ? where do you put the $group variable etc, i cant see it at the top etc. Edited by Scorpio
Posted (edited)

I assume the header of the code is missing to include the Group, TargetOU etc in the CSV?

 

Also What should $Target represent and should this be on the CSV ?

 

Do i need StudentID?

Edited by Scorpio
Posted (edited)

Also what is Prefix is this the DOMAINAME/ in the users ad? Also is the ADD to group code missing at the bottom ? Where is the group name added ? Sorry for all the questions.

 

Thanks

Edited by Scorpio
Posted
How does it know what OU or Group to put the user in ? where do you put the $group variable etc, i cant see it at the top etc.

 

In that script it's hard coded in the main loop :

 

# Move to appropriate OU

$MoveStatus=MoveStudentUser $UserName "OU=Pre16"

 

Next version I will move it into the CSV.

 

$Target is subroutines local holding variable for the parameter that is passed to the routine.

 

DOMAINNAME/ is the NT workgroup style name - generally the one you use when you log into a domain computer : DOMAINNAME/username

 

There is a function to add a user to a group but the call in not in the main loop. That's an oversight!

 

 

The code was posted as a help for people wanting to do the same in powerscript. It's not very polished!

Posted

Below an update to the create users script. I have just used this to create our new intake so it does work. Some errors were apparent but simply running it a second time seemed to correct them (mostly mailbox enable was failing but some ACL's didn't go through first time either). I suspect this may be down to propagation of the account details through our 3 DC's.

 

The script is provided more as a help to anyone who is trying to do this with powershell rather than with the expectation that you will be able to take this and simply run it as is. There are sill some assumptions baked into the script that are specific to us (the temporary OU for example or the Default Override function). However, if like me powershell is relatively new to you and you are struggling to know how to do this stuff, it should be some help.

 

The columns expected in the CSV are documented at the top. There is a function "default override" which will kick in if the CSV does not contain a targetOU column. I've removed the code as it's very specific to how we code our tutor groups. I've found it much better anyway to just do that stuff in the CSV for now.

 

The mailbox creation assumes you have the exchange commandlets available. I load them at startup by putting the commands in my profile :

 

$s = New-PSSession -ConfigurationName microsoft.exchange -ConnectionUri http:///powershell
Import-PSSession $s

 

(Obvioulsy replace with whatever is appropriate).

 

File is (hopefully) attached, code is too long to insert in-line. Any feedback or suggestions for improvements are welcome.

 

CreateUserFromCSV.ps1

Posted

:-) - This is quite a handy script to have if you use Exchange & Lync also. It don't do CSV but that could be changed! :-)

 

1. Script Prompts you to which OU you want to create the user.

2. It will create/do the following:

- Create an AD User Object

- Enable the User for Exchange

- Enable the User for Lync

- Enable the User for Exchange Unified Messaging

3. You need to provide the following via variables:

- Location of Exchange

- Location of Lync

- Default Voice Policy

- Default UM Policy

- Default Pin

- Default Password

 

##############NOTES

# Remote PowerShell must be enabled for the exchange user. You can use this command set-user alias -remotepowershellenabled $true

# Also, by default Exchange 2010/2013 use HTTP as the default remote password

 

##############VARIABLES TO CONFIGURE

#OU

## Enter the locations you want the script to be able to add users to.

$OU = ("OU=Generic Voice Mail Boxes,OU=Useraccounts,DC=contoso,DC=net",

"OU=Users,OU=Useraccounts,DC=contoso,DC=net")

 

#DefPassword

## Default password that will be used when users are created.

$DefPassword = "P@ssw0rd"

 

#exchServer

## Exchange 2010/2013 Server Name to connect

$exchServer = "exch.contoso.net"

 

#lyncServer

## Lync Server 2010/2013 Name

$lyncServer = "lyncpool01.contoso.net"

 

#Lync Defaults

## Default settings for Lync Server

$voicePolicy = "Local"

 

#Exchange Defaults

## Default settings for Exchange Server

$umPolicy = "Default Policy"

$umPin = "135790"

 

##############FUNCTIONS

function isNumeric ($x) {

$x2 = 0

$isNum = [system.Int32]::TryParse($x, [ref]$x2)

return $isNum

}

 

function SelectFromList {

param([string[]]$List,[string]$Title="Choices",[switch]$verbose=$false)

write-host $Title.padright(80) -back green -fore black

$digits = ([string]$List.length).length

$fmt = "{0,$digits}"

#display selection list

for ($LN=0; $LN -lt $List.length) {

write-host (" $fmt : $($List[$LN])" -f ++$ln)

}

#query user until valid selection is made

do {

write-host (" Please select from list (1 to {0}) or `"q`" to quit" -f ($list.length)) `

-back black -fore green -nonewline

$sel = read-host " "

if ($sel -eq "q") {

write-host " quiting selection per user request..." -back black -fore yellow

}

elseif (isNumeric $sel) {

if (([int]$sel -gt 0) -and ([int]$sel -le $list.length)) {

if ($verbose) {

write-host (" You selected item #{0} ({1})" -f $sel,$List[$sel-1]) `

-back black -fore green

}

}

else {

$sel = $null

}

}

else {

$sel = $null

}

} until ($sel)

if (isNumeric $sel) {$sel -1}

else {$null}

}

 

## Start Process

clear-host

 

# Get Creds

$UserCredential = Get-Credential

 

# Connect to Exchange

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://$exchServer/PowerShell/ -Authentication Kerberos -Credential $UserCredential

Import-PSSession $Session -AllowClobber

 

# Connect to Lync

$LyncSession = New-PSSession -ConnectionUri https://$lyncServer/OcsPowershell -Credential $UserCredential

Import-PSSession $LyncSession -AllowClobber

 

# Clear Window

clear-host

 

$sel = SelectFromList $OU " Select OU to create user."

if ($sel -ne $null) {

#Prompt Information

$accName = Read-Host " Enter Account Name (No Spaces Allowed)"

$lineURI = Read-Host " Enter Phone Number (tel:+1952xxxxxxx;ext=xxxx)"

$ext = Read-Host " Extension (xxxx)"

 

#Run Actions

New-ADUser –Name $accName –SamAccountName $accName –DisplayName $accName –Enabled $true –ChangePasswordAtLogon $false -AccountPassword (ConvertTo-SecureString $DefPassword -AsPlainText -force) -Path $($OU[$sel]) -PassThru

sleep -milliseconds 16000

Enable-Mailbox -Identity $accName

sleep -milliseconds 16000

Enable-CsUser -Identity $accName -RegistrarPool $lyncServer -SipAddressType EmailAddress

Set-CsUser -Identity $accName -EnterpriseVoiceEnabled $true -LineUri $lineURI

Grant-CsVoicePolicy -Identity $accName -PolicyName $voicePolicy

sleep -milliseconds 16000

Enable-UMMailbox -Identity $accName –UMMailboxPolicy $umPolicy -Extensions $ext –PIN $umPin –PINExpired $true

 

#Results

write-host "User created at $($OU[$sel]).`n"

}

else {

write-host "Incorrect OU Selection?`n" -back black -fore red

}

 

#Clear Session

Remove-PSSession -Session $LyncSession -Verbose

Remove-PSSession -Session $Session -Verbose

 

  • Thanks 1

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now



×
×
  • Create New...