Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Creating students with CSV file

Posted on 2014-07-10
2
Medium Priority
?
278 Views
Last Modified: 2014-07-11
I am trying output my current script to a log file. I try > "filepath" or | Out-file but the file comes up blank.  I would like the file to let me know if the user exists or doesn't exist then it created it.Here is my script.


add-PSSnapin Quest.ActiveRoles.ADManagement
Import-Module ActiveDirectory
$Users = Import-Csv C:\Temp\CreateStudents\Test\TestStudentsPS.csv
$TestHomePath = "\\Test-dataserv\students\"
$k5 = "mtnbrook.loc/District Schools/Test/School Users/Student/K-5"
$6 = "mtnbrook.loc/District Schools/Test/School Users/Student/6"
$GradeK5Array = "K","1","2","3","4","5"
$Grade6Array = "6"
$logfile = "c:\Temp\CreateStudents\Test\Teststudents.txt"
#Create a bulk mailboxes
Foreach ($User in $Users){

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
   
}

#check if the user exists
$Status = (Check-ADUser -username $User.Username).Status
If ($Status -eq 1)
{
    ("$User exists") | Out-File $logfile
} Else {
         write-host("$User does not exists creating account.")
#Modify attributes of Users account properties
      New-QADUser -Name ($User.LastName + ", " + $User.Firstname) `
      -ParentContainer "OU=Student,OU=School Users,OU=Test,OU=District Schools,DC=mtnbrook,DC=loc" `
      -Description $user.Username `
      -Company "Test" `
      -Initials $user.Initials `
      -SamAccountName $User.Username `
      -Title "Students" `
      -DisplayName ($User.LastName + ", " + $User.Firstname) `
      -FirstName $user.Firstname `
      -LastName $user.Lastname `
      -HomeDirectory ($TestHomePath + $User.Username + "\documents")`
      -Office "Test" `
      -Email ($user.Username +"@student.mtnbrook.k12.al.us") `
      -UserPassword $user.password `
      -UserPrincipalName ($user.Username +"@mtnbrook.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 "Test Students" -Member $user.Username
}

#Moves  
$OUMove =  $User.Grade
Switch ($OUMove)
{
      K {Move-QADObject $User.Username -NewParentContainer $k5}
      1 {Move-QADObject $User.Username -NewParentContainer $k5}
      2 {Move-QADObject $User.Username -NewParentContainer $k5}
      3 {Move-QADObject $User.Username -NewParentContainer $k5}
      4 {Move-QADObject $User.Username -NewParentContainer $k5}
      5 {Move-QADObject $User.Username -NewParentContainer $k5}
      6 {Move-QADObject $User.Username -NewParentContainer $6}
}
$homedir = ($CESHomePath + $User.Username)
  if (!(Test-Path $homedir)) {
    $homepath = ($homedir + "\documents")
    New-Item $homepath -type directory
    $acl = Get-Acl $homedir
    $userval = $User.Username + "@mtnbrook.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
   }

}
0
Comment
Question by:falconcurt
2 Comments
 
LVL 41

Accepted Solution

by:
footech earned 2000 total points
ID: 40189329
You should move your function creation outside of the foreach loop.  Technically it won't hurt if you leave it, it just means that it's creating the function over and over again which is a waste of resources.
To avoid overwriting the file each time through the loop, use Add-Content (or if you have PS 3.0 you can use Out-File with the -append parameter).  In the below I have both Write-Host commands for some on-screen output as well as writing to the log file at around lines 44-49.
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\CreateStudents\Test\TestStudentsPS.csv
$TestHomePath = "\\Test-dataserv\students\"
$k5 = "mtnbrook.loc/District Schools/Test/School Users/Student/K-5"
$6 = "mtnbrook.loc/District Schools/Test/School Users/Student/6"
$GradeK5Array = "K","1","2","3","4","5"
$Grade6Array = "6"
$logfile = "c:\Temp\CreateStudents\Test\Teststudents.txt"


#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" -ForegroundColor Green
        "$($User.username) exists" | Add-Content $logfile
    } 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=Test,OU=District Schools,DC=mtnbrook,DC=loc" `
        -Description $user.Username `
        -Company "Test" `
        -Initials $user.Initials `
        -SamAccountName $User.Username `
        -Title "Students" `
        -DisplayName ($User.LastName + ", " + $User.Firstname) `
        -FirstName $user.Firstname `
        -LastName $user.Lastname `
        -HomeDirectory ($TestHomePath + $User.Username + "\documents")`
        -Office "Test" `
        -Email ($user.Username +"@student.mtnbrook.k12.al.us") `
        -UserPassword $user.password `
        -UserPrincipalName ($user.Username +"@mtnbrook.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 "Test Students" -Member $user.Username
    }

    #Moves   
    $OUMove =  $User.Grade
    Switch ($OUMove)
    {
        K {Move-QADObject $User.Username -NewParentContainer $k5}
        1 {Move-QADObject $User.Username -NewParentContainer $k5}
        2 {Move-QADObject $User.Username -NewParentContainer $k5}
        3 {Move-QADObject $User.Username -NewParentContainer $k5}
        4 {Move-QADObject $User.Username -NewParentContainer $k5}
        5 {Move-QADObject $User.Username -NewParentContainer $k5}
        6 {Move-QADObject $User.Username -NewParentContainer $6}
    }
    $homedir = ($CESHomePath + $User.Username)
    if (!(Test-Path $homedir)) {
        $homepath = ($homedir + "\documents")
        New-Item $homepath -type directory 
        $acl = Get-Acl $homedir
        $userval = $User.Username + "@mtnbrook.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
 

Author Comment

by:falconcurt
ID: 40191192
Thanks footech, that got me started with the correct method to output to log file. Thanks !!
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

Let's recap what we learned from yesterday's Skyport Systems webinar.
A bad practice commonly found during an account life cycle is to set its password to an initial, insecure password. The Password Reset Tool was developed to make the password reset process easier and more secure.
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the adminiā€¦
This video shows how to use Hyena, from SystemTools Software, to update 100 user accounts from an external text file. View in 1080p for best video quality.

810 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