0

I have a pretty standard AD account creation script that I created, but need to customize it to fit my needs and that's where I'm having trouble... I added a ability to create a txt or csv file based on searching a OU and made the search filter for accounts created within the last day that includes the username and password of the account(need password for other services that will be created, non-ldap), the passwords are randomly generate through a PowerShell Function.

But when ran, it only ever includes 1 username and no password, Or it will loop through and make 3-4 log files when I only want one. Any Suggestions on how to make 1 log file with all accounts created? I'm pretty sure it has to do with the location of the csv or txt file location within the script, still learning PowerShell :)

#EDIT 3/14/2018

**gabriel-luci - The way you suggested worked. However, after talking with several people they asked if it could be a CSV. I have the CSV function working outside of this script. But I need it do do the same thing the other one was doing just in a csv format with headers of "Username,Password" Any Idea's? Thanks for your help! # Below is the part that should be writing to the CSV.. When I separate this out into another PS script, it works. It should loop through the CSV and for every username write it with its password. But when I put it in with the account creation script, it doesn't write the username or password and I check my powershell script and it's not commented out, I think the Stackoverflow thing is formatting what i posted weirdly. Or is there a better way to do what I'm attempting?

###
$CSV | ForEach-Object {
$FIRST = $_.FIRST_NAME
$LAST = $_.LAST_NAME
$USER = "$FIRST" + "$LAST"
$csvadd = $USER + "," + $Student_Password
$csvadd | Out-File $filename -Append -Encoding ASCII

###

Import-Module ActiveDirectory
#Imports CSV File and Starts Loop
$CSV = Import-CSV "C:\ActiveDirectory\NewStudent.csv" | % { 
#Create Variables
#
$First_Name = $_.FIRST_NAME
$Last_Name = $_.LAST_NAME
$Username = "$First_Name" + "$Last_Name"
$Student_Number = $_.Student_Number
#Shouldn'tBeNeeded-$Lunch_ID = $_.Lunch_ID
$Grade_Level = $_.Grade_Level
$School_Name = $_.School_Name
$School_Abbr = $_.School_Abbr
$Graduation_Year = $_.graduation_year
$EmployeeID = $Student_Number
$StudentPassword = New-Password
$SecurePassword = (ConvertTo-SecureString -AsPlainText $StudentPassword -
Force)
$FullName = "$First_Name" + " "+ "$Last_Name"
$UserPN = $Username + "@home.virtual.local"
$Email = $Username + "@home.virtual.local"
#NotNeeded-$LegacyEmail = $_.WEB_ID + "@home.virtual.local"
$Description = "Grade " + $Grade_Level
$Path = "OU=ScriptTesting,OU=Test Accounts,OU=People,DC=Home,DC=Local"
#$Path = "OU=" + $Grade_Level + ",OU=" + $School_Abbr + 
",OU=ScriptTesting,OU=Test Accounts,OU=People,DC=Home,DC=Local"
#NotNeeded-$GradeLevelGroup = "Stu_" + $Grade_Level + "_Grade"
#$HomeFolder = "\\staff-files\" + "$Graduation_Year\" + $Username
#
$curdate = Get-Date -Format o | foreach {$_ -replace ":", "."}
#curdate = Get-Date -format s | foreach {$_ -replace ":", "."}
$filename = "C:\Student_Accounts\logs\Usernames_Passwords-" + $curdate + 
".csv"
$CSVHeader = "Username,Password"
$CSVHeader | Out-File $filename -Encoding ASCII
##
$ADUser = Get-ADUser -LDAPFilter "(sAMAccountName=$Username)"
#
If ($ADUser -eq $Null) 
{

New-ADUser $FullName -GivenName $First_Name -Surname $Last_Name `
-SamAccountName $Username -UserPrincipalName $UserPN `
-AccountPassword (ConvertTo-SecureString $StudentPassword -AsPlainText -
 force) `
-Office $School_Name `
-Title $Graduation_Year `
-EmployeeID $Student_Number `
-DisplayName $FullName `
-Department $Grade_Level `
-Description $Description  `
-EmailAddress $Email `
-Path $Path `
-PassThru | Enable-ADAccount
#
Sets Home Directory
New-Item -Name $Username -ItemType -Path $HomeFolder | Out-Null
Set-ADUser $Username -HomeDirectory $HomeFolder -HomeDrive S:
Sets ACL List
$ACL= Get-ACL $HomeFolder
$ACL.SetAccessRuleProtection($true, $True)

#Add User to AD Grade Level Group

#Add-ADGroupMember -Identity $GradeLevelGroup -Members $Username

#Small Pause to give time for AD Account to be created before resetting 
   password
Start-Sleep -s 30

#Reset Password
Set-ADAccountPassword -Identity $Username -NewPassword $SecurePassword -
Reset | Set-ADuser -ChangePasswordAtLogon $False -PasswordNeverExpires 
$True -CannotChangePassword $True

Write-Host $StudentPassword
#Write-Host "Account Created" $Username
#Write-Host "Password for" $Username "Is" $StudentPassword
#Return $Username
#Return $StudentPassword

$CSV | ForEach-Object {
$Username = "$First_Name" + "$Last_Name"
$csvadd = $Username + "," + $Student_Password
$csvadd | Out-File $filename -Append -Encoding ASCII
}
}
}
1
  • You can include a variable inside a string if the string uses double quotes to define it eg: $Path = "OU=$Grade_Level,OU=$School_Abbr,OU=User,DC=home,DC=virtual,DC=local" or $UserPN = "[email protected]" Doing this saves using excessive + everywhere. The only gotcha is $_.X where you would need to wrap it in $() eg: $LegacyEmail = "$($_.WEB_ID)@home.virtual.local" Commented Mar 13, 2018 at 12:51

1 Answer 1

1

Your log file name includes the time, including seconds and milliseconds, so because you regenerate the file name in each iteration of the loop, the log file name is changing each time, and you get multiple log files.

You can solve this by determining the name of the log file before you enter the loop, so that every iteration of the loop is using the same file.

Move these lines up to the top of your script, outside the loop:

$curdate = Get-Date -Format o | foreach {$_ -replace ":", "."}
$filename = "C:\ActiveDirectory\Logs\AccountCreation\AccountsCreated-" + $curdate + ".txt"

The lines that output to the file are also overwriting the file (Out-File overwrites by default):

Write-Host $filename
Write-Output $log | Out-File $filename

There are actually 3 ways you can append to a file. Take your pick. All 3 do exactly the same thing:

$log | Out-File $filename -Append
$log | Add-Content $filename
$log >> $filename

You don't need to use Write-Host or Write-Output.

Edit: This is the part I'm talking about where I say to remove the loop:

#$CSV | ForEach-Object { ### You don't need this ForEach
#Just use the next 3 lines
$Username = "$First_Name" + "$Last_Name"
$csvadd = $Username + "," + $Student_Password
$csvadd | Out-File $filename -Append -Encoding ASCII
#}
Sign up to request clarification or add additional context in comments.

14 Comments

Thanks for the clarification.. It makes sense why it kept making new log files now. Just want to make sure I understand you, When you say outside of my loop, do you mean above "Import-CSV "Path" or above "If ($ADUser -eq $Null)? Going to test shortly
Above your Import-CSV line.
Tested what you said and it worked.. Edited original post to reflect changes that I discovered\made. Thank you for helping me get the old log thing working
You're still setting $filename (and writing the header) inside the loop. I'm guessing you are seeing the header repeated inside the file?
Sometimes... I was seeing duplicated headers but not filename
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.