locked
Help with CSV Exporting in PowerShell RRS feed

  • Question

  • Evening all,

    I am writing a script to create a new user in AD (the 'nth' millionth script to do this, I know) but it's for educational purposed really.

    The script in its entirety runs as I'd like it to, except the final part 'Export-CSV' and it's driving me round the bend as to why it isn't working. 

    Can someone please take a look and explain to me what I'm doing wrong?

    #$fn = First name
    $fn = Read-Host -Prompt "Enter the employees forename"
    
    #$ln = Last name 
    $ln = Read-Host -Prompt "Enter the employees surname"
    
    #split the last name into an array 
    $lnsplit = $ln.ToCharArray()
    
    #call the first letter of the last name and assign it to a variable
    $lnfl = $lnsplit[0]
    
    #Combines the first name and the first letter of the surname
    $username = -join($fn,$lnfl)
    
    $password = "sdpjsopsgj0485!&*"
    
    #New domain user creation process
    New-ADUser -Name ($fn,$ln -join " ") -GivenName $fn -Surname $ln -SamAccountName $username -UserPrincipalName "$username@alqotaibi.com" -DisplayName ($fn,$ln -join " ") -Enable $true -AccountPassword (ConvertTo-SecureString -AsPlainText $password -Force) -EmailAddress "$username@alqotaibi.com" | 
    
    #Exports the new user data into a .CSV file
    Get-ADUser -Filter 'Surname -Like $ln' -Properties * | Export-CSV -Path "C:\Users\ReeceA\Desktop\$username.csv"

    The user is created in AD successfully, and the .CSV is created successfully with the correct filename but when I open it, it is blank.

    N.B If I run the following in PowerShell, after creating a user it works fine:

    $ln = Read-Host -Prompt "Enter the employees surname"

    and then

    Get-ADUser -Filter 'Surname -Like $ln' -Properties * | Export-CSV -Path "C:\Users\ReeceA\Desktop\$username.csv"

    Many thanks in advance,

    Reece

    Monday, April 30, 2018 10:43 PM

Answers

  • Get-User returning all properties will not work.  It will create an unreadable CSV file.  You must select the specific proeprties you want.

    THe filter must use double quotes or it won't work. "LIKE" requires a wildcard to work.

    Get-ADUser -Filter "Surname -Like '$ln*'" -Properties DIsplayName, Surname, GivenName |
         Export-CSV -Path "C:\Users\ReeceA\Desktop\$username.csv"

    You need to start by learning the basics of PowerShell.  Guessing will cause you months of wasted time.


    \_(ツ)_/

    Monday, April 30, 2018 11:00 PM