none
AD account creation HELP! RRS feed

  • Question

  • Hello, I was wondering if I could get some help on a script I created. Our environment is setup with Windows server 2008 R2 (just recently upgraded to 2012 R2)  we do not use ADFS servers we use DirSync to import AD to O365 and we use Password sync from Messageops so AD passwords are passed along to O365.

    What I need help on is truncating the users sAMaccountName (the pre-windows 2000) as any user with over 20 characters fails to create. The format we are using is Firstname.Lastname, if I manually create the account ADUC automatically truncates the logon name. So that is one thing I need help on.

    The second part I need help on is exporting to the CSV file portion. I have it set up now to basically pull the LastName, mail and ID headers from the first CSV file and rename the expressions to Last_name, email and id_num and input the values from those columns into the new columns. However it does this even if part of the script failed because I have it set up that way. I need it to query the AD and verify those accounts have been created and input those verified accounts into the new CSV file and email me if any user is not created.

    Below is the script I run, everything works I just need help truncating SamAccountName (pre-windows 200) and after script runs to verify if all accounts were made and export them to a CSV file containing LastName, email and ID number.

    The CSV file that I use is laid out like this...

    SamAccountName, FirstName, LastName, Displayname, Mail, ID, UPN, Company, Department, Title, Phone, Password, path

    The exported CSV is laid out like this...

    Last_name, email, id_num

    What this script does is import a CSV file, takes data from the CSV and creates the AD account. After the account is created it pauses for 15 mins to allow the account to replicate out to O365 (I set up Directsync to update every 15mins vs the 3 hour default).


      

    Import-Module ActiveDirectory #CREATE ACTIVE DIRECTORY ACCOUNT import-csv "C:\NewStudents\o365-Students.csv" | ForEach-Object { New-ADUser -Name $_.SamAccountName -UserPrincipalName ($_.UPN + "@my.domain.com") -GivenName $_.FirstName -Surname $_.LastName -Displayname $_.displayname -EmailAddress $_.mail -path $_.path -AccountPassword (ConvertTo-SecureString -AsPlainText $_.Password -Force) -title "Student" -company "My Company" -department $_.Department -employeeID $_.ID -HomePhone $_.Phone -Enabled $true -passwordneverexpires $true } import-csv "C:\NewStudents\o365-Students.csv" | ForEach-Object {Set-ADUser -identity $_.SamAccountName -Add @{targetAddress="SMTP:" + $_.UPN + "@domain.mail.onmicrosoft.com"}} import-csv "C:\NewStudents\o365-Students.csv" | ForEach-Object {Set-ADUser -identity $_.SamAccountName -Add @{ProxyAddresses="smtp:" + $_.UPN + "@domain.mail.onmicrosoft.com"}} import-csv "C:\NewStudents\o365-Students.csv" | ForEach-Object {Set-ADUser -identity $_.SamAccountName -Add @{ProxyAddresses="smtp:" + $_.UPN + "@domain.onmicrosoft.com"}} import-csv "C:\NewStudents\o365-Students.csv" | ForEach-Object {Set-ADUser -identity $_.SamAccountName -Add @{ProxyAddresses="SMTP:" + $_.UPN + "@my.domain.com"}} #ADD USERS TO SPECIFIED GROUPS import-csv "C:\NewStudents\o365-Students.csv" | ForEach-object { Add-ADGroupMember -identity "Password Sync" -Member $_.SamAccountName} import-csv "C:\NewStudents\o365-Students.csv" | ForEach-object { Add-ADGroupMember -identity "All Students" -Member $_.SamAccountName}

    start-sleep -s 900


    After the 15 min pause the script then continues by signing into my Office 365 with my credentials saved as a secure-string. (To save the password as a secure-string I did this "read-host -prompt "Enter password to be encrypted in mypassword.txt " -assecurestring | convertfrom-securestring | out-file C:\Office365\cred.txt") 

    #Input username and password for O365 admin account
    cd C:\Office365
    $password = Get-content C:\Office365\cred.txt | ConvertTo-SecureString
    $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ebert98@my.stmary.edu,$password
    $s = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $cred -Authentication Basic -AllowRedirection
    Connect-MsolService -Credential $cred

    After it's signed into Office 365 it then creates a special O365 license for students disabling everything but Exchange Online.

    #Creates special O365 license for students disabling everything but Exchange Online
    $myO365Sku = New-MsolLicenseOptions -AccountSkuId domain:STANDARDWOFFPACK_STUDENT -DisabledPlans MCOSTANDARD,SHAREPOINTWAC_EDU,SHAREPOINTSTANDARD_EDU
    start-sleep -s 1
    
    import-csv "C:\NewStudents\o365-Students.csv" | ForEach-Object {Set-MsolUser -UserPrincipalName ($_.UPN + "@my.domain.com") -UsageLocation US}
    import-csv "C:\NewStudents\o365-Students.csv" | ForEach-Object {Set-MsolUserLicense -Userprincipalname ($_.UPN + "@my.domain.com") -AddLicenses domain:STANDARDWOFFPACK_STUDENT -LicenseOptions $myO365Sku}


    Then I need the script to output to a CSV file first query the AD to verify if the account exists. Currently it is just set up like this...

    #Outputs csv file to update EX
    Import-Csv C:\NewStudents\o365-Students.csv | select @{Name="Last_name";Expression={$_."LastName"}},@{Name="email";Expression={$_."mail"}},@{Name="id_num";Expression={$_."ID"}} | Export-Csv -Path c:\NewStudents\email-idnumupdate.csv –NoTypeInformation

    The very last thing the script does is to reset the newly created student AD password so MessageOps password sync utility can grab the new password.

    foreach($user in (import-Csv C:\NewStudents\o365-Students.csv))
    {
        Write-Host "Setting Password for $($User.UPN)"
        $ds = new-Object System.DirectoryServices.DirectorySearcher([ADSI]"","(&(objectcategory=user)(sAMAccountName=$($user.UPN)))")
        $usr = ($ds.Findone()).GetDirectoryEntry()
        $usr.SetPassword($user.password)
        $usr.SetInfo()
    }

    Any help with the truncating sAMaccountName and exporting CSV file after query of AD verifies the account is there would be extremely helpful. Also if an account is skipped/errors out to have it email me that the account was not created.

    Thanks!




    • Edited by usmagent Monday, February 24, 2014 10:25 PM added bold letters to clarify what I am needing
    Monday, February 24, 2014 8:07 PM

Answers

All replies

  • It would be far better if you break down your queries and ask individual and very specific questions.

    It's doubtful others have the time to read through all of the above, track down each requested problem, and then fix them for you.

    Generally, people have more time to answer specific, targeted questions rather than a broad "I need someone to help me redesign this entire system" kind of question.

    Bill

    Monday, February 24, 2014 9:16 PM
    Moderator
  • I was just trying to give enough information and background to what I have and have done.

    All I need help with is in the first part at the top where I said, "

    What I need help on is truncating the users sAMaccountName (the pre-windows 2000) as any user with over 20 characters fails to create. 

    The second part I need help on is exporting to the CSV file portion. I need it to query the AD and verify those accounts have been created and input those verified accounts into the new CSV file and email me if any user is not created."

    Sorry if it was confusing, I was just explaining what I have done. And laying it all out in case someone tries to do something similar to what I have done. The script works I just need help with the above.

    • Edited by usmagent Monday, February 24, 2014 10:11 PM
    Monday, February 24, 2014 10:08 PM
  • I will be honest and say I am not going to read through your first post. TL;DR.

    So let's start with the first question.

    What specifically do you mean by 'truncating the users sAMAccountName'?

    A sAMAccountName is a string. You can use a string's Substring method to chop a string to meet a length:


    PS C:\> $string = "This is a long string"
    PS C:\> $string.Substring(0,20)
    This is a long strin
    

    Bill

    Monday, February 24, 2014 10:42 PM
    Moderator
  • Hi,

    Truncating input example:

    Import-Csv .\userList.csv | ForEach {
    
        if ( ($_.SamAccountName).Length -gt 20 ) {
    
            $SamAccountName = $_.SamAccountName.Substring(0,20)
    
        }
    
        else { $SamAccountName = $_.SamAccountName }
    
        $SamAccountName
    
    }

    Verification and export to CSV example, assumes you're using the same input file which needs to be truncated:

    Import-Csv .\userList.csv | ForEach {
    
        if ( ($_.SamAccountName).Length -gt 20 ) {
    
            $SamAccountName = $_.SamAccountName.Substring(0,20)
    
        }
    
        else { $SamAccountName = $_.SamAccountName }
    
        try {
    
            $userDetails = Get-ADUser -Identity $SamAccountName
        }
    
        catch {}
    
        If ($userDetails) {
            
            $props = @{
                UserName = $SamAccountName
                ExistsInAD = 'YES'
            }
        }
    
        Else {
    
            $props = @{
                UserName = $SamAccountName
                ExistsInAD = 'NO'
            }
    
        }
    
        New-Object PsObject -Property $props
    
        Remove-Variable userDetails,props -ErrorAction SilentlyContinue
    
    } | Sort-Object UserName | Export-Csv .\userVerification.csv -NoTypeInformation


    Don't retire TechNet! - (Don't give up yet - 12,700+ strong and growing)

    Tuesday, February 25, 2014 12:14 AM
  • Mike this is usmagent was having problems with my account so I just set up a new one real fast. When it comes to truncating the samaccountname I noticed if I manually create the account the length of the samaccountname is not an issue as the "User logon name:" accepts longer samaccountnames and "User logon name (pre-windows 2000):" automatically truncates the samaccountname.

    User logon name: more than 20 characters

    User logon name (pre-windows 2000): 20 characters or less

    It seems when my script runs this causes the account to fail. The script just errors out and any name after the one that failed, fail to get created. 

    So I don't need to truncate the entire samaccountname just have it truncate the (pre-windows 2000) name.

    Any thoughts?

     
    Tuesday, March 18, 2014 7:56 PM
  • The SamAccountName is the 'pre-windows 2000 logon name'. The 'user logon name' property you're referring to is the UPN.

    Don't retire TechNet! - (Don't give up yet - 12,700+ strong and growing)

    Tuesday, March 18, 2014 8:03 PM