Import-csv and New-ADUser issue

Hi there,
I am fairly new to PS (and this site) and I don't understand what I am doing wrong. (I changed some domain settings where applicable to not the reflect the real-world scenario, just an example)
CSV content:
Firstname,Lastname,Maildomain,SAM,OU,Password,Description
User,Test01,contoso.com,utest01,OU=Standard Users,OU=Users,DC=domain,DC=loc,P@ssw0rd,Test User
PS script:
$Users = Import-Csv -Delimiter "," -Path "C:\Userlist-sn.csv"
foreach ($User in $Users)
$Displayname = $User.Firstname + " " + $User.Lastname
$UserFirstname = $User.Firstname
$UserLastname = $User.Lastname
$OU = "$User.OU"
$SAM = $User.SAM
$UPN = $User.Firstname + "." + $User.Lastname + "@" + $User.Maildomain
$Description = $User.Description
$Password = $User.Password
New-ADUser -Name "$Displayname" -DisplayName "$Displayname" -SamAccountName $SAM -UserPrincipalName $UPN -GivenName "$UserFirstname" -Surname "$UserLastname" -Description "$Description" -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true -Path "$OU" -ChangePasswordAtLogon $false –PasswordNeverExpires $true -server domain.loc
I am getting the following error:
New-ADUser : The object name has bad syntax
At C:\Windows\System32\WindowsPowerShell\v1.0\import-test.ps1:12 char:15
+ New-ADUser <<<< -Name "$Displayname" -DisplayName "$Displayname" -SamAccountName $SAM -UserPrincipalName $UPN -GivenName "$UserFirstname" -Surname "$UserLastname" -Description "$Description" -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true -Path "$OU" -ChangePasswordAtLogon $false –PasswordNeverExpires $true -server domain.loc
+ CategoryInfo : NotSpecified: (CN=User Test01...t Test User}.OU:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : The object name has bad syntax,Microsoft.ActiveDirectory.Management.Commands.NewADUser
Now that I am writing this question it kind of dawned on me whether or not the problem is with the csv, as delimiter is "," and the OU value has commas in it and it destroys syntax. If this is so then my question would be, how to save the input
so the values are retained correctly? Is the New-ADUser command itself ok?
Thank you all.

Hi,
Now that I am writing this question it kind of dawned on me whether or not the problem is with the csv, as delimiter is "," and the OU value has commas in it and it destroys syntax.
Are the OUs quoted inside of the CSV? If so, the commas inside should be fine.
Here's an easy test to see if your problem is with the input:
Quoted OU path:
PS C:\Scripts\PowerShell Scripts\Misc Testing\5-21-2014> Import-Csv .\Userlist-sn.csv
Firstname : User
Lastname : Test01
Maildomain : contoso.com
SAM : utest01
OU : OU=Standard Users,OU=Users,DC=domain,DC=loc
Password : P@ssw0rd
Description : Test User
Unquoted OU Path:
PS C:\Scripts\PowerShell Scripts\Misc Testing\5-21-2014> Import-Csv .\Userlist-sn2.csv
Firstname : User
Lastname : Test01
Maildomain : contoso.com
SAM : utest01
OU : OU=Standard Users
Password : OU=Users
Description : DC=domain
Don't retire TechNet! -
(Don't give up yet - 12,830+ strong and growing)

Similar Messages

  • Import-CSV and PSObject

    Hello,
    I have a problem to get below approach.
    Imagine that I have csv file with content as below:
    Head1;Head2;Head3;
    xyz;---;---;
    ---;zyx;---;
    ---;---;xzy;
    123;---;---;
    ---;213;---;
    ---;---;321;
    I'd like to import this file to powershell (import-csv) and put whole content to PSObject that:
    1. First line contains only headers - that if I put $PSObj[1] I'll get all headers
    2. All three "letters lines" are joined to one PSObject item - that if I put "$PSObj[1]" I'll get all these 3 lines
    3. All three "numbers lines" are joined to one PSObject item - that if I put "$PSObj[2]" I'll get all these 3 lines
    I need points 2 and 3 because I need to compare imported information on subject level (Test1 or Test2) and not to compare information on each line level.
    One facilitation (I hope) is that each PSObject item begines when in a row in first column is not "---" value. And end of this item is one row before a row where in first colum is different value than "---" (it is shown on above example)
    Has anyone an idea how to do it?

    Hi D'Thompson,
    Yes you are right, I think that to accomplish my idea I need to divide csv lines/items into separate objects as below:
    Object 1 (5 items)
    Head1 : TestName1
    Head2 : ---
    Head3 : ---
    Head4 : ---
    Head5 : Generic
    Head6 : 1/8/2015 2:48:06 PM
    Head7 :
    Head1 : ---
    Head2 : ---
    Head3 : CommonDeploymentUtility
    Head4 : 6.4.0.4025
    Head5 : ---
    Head6 : ---
    Head7 :
    Head1 : ---
    Head2 : ---
    Head3 : CommonUtility
    Head4 : 6.4.0.4025
    Head5 : ---
    Head6 : ---
    Head7 :
    Head1 : ---
    Head2 : ---
    Head3 : Ionic
    Head4 : 1.9.1.5
    Head5 : ---
    Head6 : ---
    Head7 :
    Head1 : llllllllll
    Head2 : llllllllll
    Head3 : llllllllll
    Head4 : llllllllll
    Head5 : llllllllll
    Head6 : llllllllll
    Head7 : llllllllll
    Object 2 (9 items)
    Head1 : TestName2
    Head2 : ---
    Head3 : ---
    Head4 : ---
    Head5 : Generic
    Head6 : 6/17/2013 9:04:22 AM
    Head7 :
    Head1 : ---
    Head2 : Experiences.PublishingExperiences
    Head3 : ---
    Head4 : ---
    Head5 : ---
    Head6 : ---
    Head7 :
    Head1 : ---
    Head2 : ---
    Head3 : Experiences.ListDefinitions.ExperienceLists
    Head4 : 1.0.0.0
    Head5 : ---
    Head6 : ---
    Head7 :
    Head1 : ---
    Head2 : Material.News
    Head3 : ---
    Head4 : ---
    Head5 : ---
    Head6 : ---
    Head7 :
    Head1 : ---
    Head2 : ---
    Head3 : Material.News
    Head4 : 1.0.0.0
    Head5 : ---
    Head6 : ---
    Head7 :
    Head1 : ---
    Head2 : Material.PublishingMaterials
    Head3 : ---
    Head4 : ---
    Head5 : ---
    Head6 : ---
    Head7 :
    Head1 : ---
    Head2 : ---
    Head3 : Material
    Head4 : 1.0.0.0
    Head5 : ---
    Head6 : ---
    Head7 :
    Head1 : ---
    Head2 : Material.Search
    Head3 : ---
    Head4 : ---
    Head5 : ---
    Head6 : ---
    Head7 :
    Head1 : llllllllll
    Head2 : llllllllll
    Head3 : llllllllll
    Head4 : llllllllll
    Head5 : llllllllll
    Head6 : llllllllll
    Head7 : llllllllll
    So all I need is code that import csv file and divide content to many objects according to below rules
    Beginning (first item) of an object is csv item where first column/position (Head1) value is not like "---" and not like "llllllllll".
    Last item of such object would be csv item where first column/position (Head1) value is "llllllllll"
    The code should also be able to create many PSObjects (as variables) with unique names (e.g. $PSObj1, $PSObj2, PSObj3,...).

  • Need to import csv and manipulate one column

    I have a monthly report output by an FTP program into CSV format. The CSV file has headers and 3 columns:
    1) a group name
    2) the number of transfers that group made
    3) the total size of all their transfers (in bytes)
    Example (with headers and 6 rows of data for 7 rows total):
    "monthly transfers","sum of monthly transfers","sum of file size"
    "group1 (Prod to Dev)","26","11556381672"
    "group2 (Prod to Dev)","5","348197396"
    "group3 (Prod to Dev)","14","1272913379"
    "group1 (Dev to Prod)","0","0"
    "group2 (Dev to Prod)","1976","2036311426"
    "group3 (Dev to Prod)","1","131"
    I have been asked to write a script that will convert the bytes to megabytes and then sort based on group name and export the new data so auditors (non-technical people) can review it.
    I've worked with Excel a bunch in Powershell (I.E. opening a com object and writing directly to a cell) and I'd prefer to do it that way, but the server this script needs to run on doesn't have MS Office installed and can't have anything else installed on
    it, so I'm trying to learn about import-csv and such. I've come up with this:
    $file = "C:\ftp\ftp_report.csv"
    $csv = import-csv $file
    $csv | sort "monthly transfers"
    The part I'm stuck on is converting that third column from bytes to megabytes. I know that in Powershell I can do "X / 1mb" to convert a number from bytes to megabytes, but I'm not sure of how best to do this in a specific column of a CSV file.
    Should I create a hash table? Should I count the number of rows and then do a "foreach" on
    $csv[0].'sum of file size' / 1mb
    Am I overthinking this and there's a really easy way to manipulate all values in a column?
    Thank you in advance.
    [email protected]

    Probably like this, right at the parameter:
    ("{0:N2}" -f ($row.'sum of file size' / 1mb))
    There's no place like 127.0.0.1

  • Import-CSV and Takeown.

    I'm currently trying to come up with a way to search an entire folder directory to find all objects that a particular user is owner to, export that list to csv, then import that csv and using takeown to grant local Administrators Owner.
    Scouring the internet, I've been able to come up with this Powershell script to scan a directory and export the findings to a csv.
    param(
    [string]$username = "NameofUserSearchingFor",
    [string]$logfile
    Set-ExecutionPolicy Unrestricted
    if ($logfile -eq "") {
    $logfile = "c:\" + $username + "-Owner.csv"
    Write-Host "Setting log file to $logfile"
    #Path to search in
    [String]$path = "c:\TestFolder"
    [String]$AD_username = "Domain\" + $username
    #check that we have a valid AD user
    if (!(Get-ADUser $AD_username)){
    Write-Host "ERROR: Not a valid AD User: $AD_username"
    Exit 0
    Write-Output "$username" | Out-File -FilePath $logfile
    $files = Get-ChildItem $path -Recurse
    ForEach ($file in $files)
    $f = Get-Acl $file.FullName
    if ($f.Owner -eq $AD_username)
    Write-Output $file.FullName | Out-File -FilePath $logfile -Append
    exit 0
    That script exports data in the form of:
    NameofUserSearchingFor
    C:\TestFolder\TestFolder1
    C:\TestFolder\TestFolder2
    C:\TestFolder\TestFolder1\test1.txt
    C:\TestFolder\TestFolder2\test2.txt
    I'd like to use takeown to read each line of text and take ownership for local Administrators.  
    The script i'm trying to use doesn't do anything though.
    #Local Admininstrator Take Ownership
    $rows = Import-Csv "c:\NameofUserSearchingFor-Owner.csv"
    ForEach ($row in $rows)
    takeown /A /F $row
    Perhaps I'm going about this all wrong.  I'm relatively new to Powershell and have been trying to come up with a way to do this for the past 3 days.
    Any assistance would be greatly appreciated!
    *Update*
    If I reconfigure the takeown portion a bit to this:
    #Local Admininstrator Take Ownership
    $Path = "c:\NameofUserSearchingFor-Owner.csv"
    $rows = Import-Csv $Path
    ForEach ($line in $rows)
    takeown /A /F $Path
    The result is:
    SUCCESS: The file (or folder): "c:\NameofUserSearchingFor-Owner.csv" now owned by the administrators group.
    But will repeat as many times as there are lines of text in the csv.  So if there are 4 lines of text in the csv, that line will repeat 4 times.  I find it interesting that it knows how many lines there are but instead of granting local Administrator
    the owner to the path specified in the line it will instead grant local Administrator to the csv file.

    That is because you are takingownership of the CSV.
    ForEach ($line
    in$rows){
        takeown /A
    /F $Path
    should be:
    ForEach ($line
    in$rows){
        takeown /A
    /F $line
    ¯\_(ツ)_/¯

  • Import-csv and export-csv

     Hi everyone,
    How do I modify the script so that I see all the entries in the computers_result.csv file.  As it stands only the last entry in the computers.csv shoes up in the computers_result.csv file.  Thanks so much.
    Import-Csv C:\computers.csv | ForEach-Object {
    $computername = $_.computer
    $result = get-adcomputer $computername -Properties description  | select Name,Description
    $result | export-csv C:\computers_result.csv

    Try this and let me know
    $result = @()
    Import-Csv C:\computers.csv | ForEach-Object {
    $computername = $_.computer
    $result += get-adcomputer $computername -Properties description | select Name,Description
    $result | export-csv C:\computers_result.csv
    Regards Chen V [MCTS SharePoint 2010]

  • SCOM 2012 and New-WebServiceProxy issue to access C:\Windows\Temp

    I am currently development management pack for data center equipment. This management pack connect to a WCF service (hosted as windows service on one of the management servers in the management group). WCF service works as intermediate layer between equipment
    and management pack. It connects to equipment and does following task periodically:
    1. Connect to equipment
    2. Generate inventory information from equipment
    3. Collect fault information
    4. Map inventory information to faults
    Management pack connects to WCF service and requests the inventory information, fault information etc. Following is the way to access WCF service.
    $wcfConnection = New-WebServiceProxy http://<fqdn of management server>:8732/DataCenterEquipmentService
    Now we use connection object to retrieve the data.
    $wcfConnection.GetFaults() will provide me fault data as XML and using MOM.ScriptAPI object we insert data to SCOM.
    Now the issue is when create WCF connection object, it throws errors:
    Could not load file or assembly 'file:///C:\Windows\TEMP\gjdtzucb.dll' or one of its dependencies. The system cannot find the file specified.
    This arbitrary dll file name is very random and every time it tries to make connection to WCF service, it throws random dll name.
    Please help me to resolve this issue.
    Thanks,
    -Mukul

    Hello Mukul, were you able to resolve this? I am getting the exact same error. Thanks.

  • Reminder Syncing Between iPhone 4 and new iPad Issues.

    Good day to everyone.
    I am currently facing some issues with the reminder syncing within iphone 4 and iPad 4th generation. The date and time of the reminder couldn't sync to either Ipad or iphone, the rest of the details is fine. So right now, I've to use the reminder without any internet or data connectivity. If i switch on, the date and time will dissapear.
    Please advise me on this. Your assistances is much very appreciated.
    Thank you.
    Kind regards,
    Daniel.L

    Hi daniellim86!
    Here is an article for you that will help you troubleshoot this issue with Reminder syncing:
    iCloud: Troubleshooting iCloud Reminders and Tasks
    http://support.apple.com/kb/ts4000
    Take care, and thanks for visiting the Apple Support Communities.
    -Braden

  • Captivate 5 export and import legend and sub title issue

    when
    i export a legend and sub title for revisiont and then import it
    i get a white text on withe background why ?
    my font on the project are white is it because of this ?
    Thanks

    let me explain better :-)
    in captivate 5 there a feature for people to export legend and sub title so some one could revise the slide text etc...
    i exprt it in word format but the doc created  we could reed the text cause the text is white on a white background
    any idea ?
    Thanks

  • Java upgrade and new Safari issues

    Just upgraded Java (55) on my iMac and now can't swipe pages with my mouse in Safari? Anyone else having this issue?

    Desktop ?
    Check your settings in System Preferences > Mouse > More Gestures
    or laptop ...
    System Preferences > Trackpad

  • PX6-300d and new disk issues

    Hello!
    I have PX6-300d with 6 2TB disks installed. I'd like to replace them with 6 4 TB disks. To save all my data first time i tried to do hot replace 2 TB disk #6 with 4 TB disk. It didn't work cause I had repeating message about disk cleaning. I did clening pocedure with diskpart.exe but nothing changed. If I replace drives with PX6-300d shut down then PX6 doesn't start. So I removed all 6 2 TB disks and installed 1 4 TB disk. Device didn't load. I started PX6 with no disks and install 4 TB disk on working PX6. I received the same situation with repeating message about disk overwriting. My new 4 TB disk is Seagate ST4000VN000 and it should be compatible with PX6. I have last firmware version installed...
    The question is: what's wrong or is there correct way to upgrade my PX6 from 2 TB disks to 4 TB disks? 
    Thank you very much for any useful information...
    Solved!
    Go to Solution.

    Hi aketkov,
    The device will ask you to overwrite any existing data when you install a new drive, even if there is not any data on the drive. You will need to allow the device to erase the disks to add them. Please follow the instruction procedure on the following support page: Upgrading the storage capacity for an Iomega network storage device
    Have questions and need answers?
    Search the database for answers to FAQ's, software/driver downloads, tutorials, news, features and more!
    LenovoEMC Support & Downloads
    LenovoEMC North America Support Contact Page

  • Customer service and new ipod issues

    i have called customer service 3 times and have been put on hold for about an hour in total, all asking me to wait for the senior adviser. i was told in my last call yesterday that the senior adviser will call me when he has time. from the service i've gotten so far, i won't be surprised if i don't get a call. why can't apple just add email support?
    basically my problem is that the top portion of the touch starts to get warm within a few minutes of using it, even if im just surfing the web or looking through the app store, and after about 20-30 minutes, it gets noticeably hot. not burning but just hot. does this happen with anyone elses 4g touch? ive been to 2 service providers and they say its cos of the wifi or some sort of app ive installed. ive restored to factory settings already but surely the wifi component shouldnt get so hot? this never happened with my 2g touch.
    i also noticed scratches on the back already on a week old touch just like my 2g and i am VERY careful. i got a replacement just because of scratches last time for it and i basically sent a photo through email which was about 2 years ago so im guessing apple removed the email support since then? apple support has gotten a lot worse and i would've probably been better off just buying off a third party for cheaper than from the online store.

    I noticed that my iPod gets hot occasionally if I use it for more than 30 mins, I mainly use it while it's in it's case, so it heats up a little.
    As for the scratches, that just seems to be the fate of most things that apple makes. Best is to try to protect it as best as you can. I have a red leather case that closes like a day planner to protect it all the way around, a plastic cover that protects it's back and a screen protector that protects it's front. Bit of overkill I know, but at $300 I don't have the money to replace it if it gets damaged.
    I bought the case from Amazon.com for about $15, Apple wanted twice that for the same kind of case.

  • New-ADUser with Import-Csv...

    trying to run this cmd from an elevated PS prompt.
    Import-CSV "C:\Users\administrator\Documents\Students.csv" | foreach {New-ADUser -SamAccountName $_.PermID -Name ($_.FirstName + " " + $_.LastName) -DisplayName ($_.FirstName + " " + $_.LastName) -Surname $_.LastName -GivenName $_.FirstName -Path $_.OU -AccountPassword
    (ConvertTo-SecureString -AsPlainText $_.Password -Force) -Enabled $true }
    and it fails with
    New-ADUser : The server is unwilling to process the request
    At line:1 char:81
    + Import-CSV "C:\Users\administrator\Documents\Students.csv" | foreach {New-ADUser <<<<  -SamAccountName $_.PermID -Nam
    e ($_.LastName + ", " + $_.FirstName) -DisplayName ($_.LastName + ", " + $_.FirstName) -Surname $_.LastName -GivenName
    $_.FirstName -Path $_.OU -AccountPassword (ConvertTo-SecureString -AsPlainText $_.Password -Force) -Enabled $true }
        + CategoryInfo          : NotSpecified: (CN=Marsh\, Stan...dents,dc=testad:String) [New-ADUser], ADException
        + FullyQualifiedErrorId : The server is unwilling to process the request,Microsoft.ActiveDirectory.Management.Comm
       ands.NewADUser
    No really sure what it means by the server is unwilling. Could it be the Account/Password Policies?
    Thanks for the help

    There are several possibilities. Among them:
    1. A -Name value is not unique in the OU.
    2. A -sAMAccountName value is not unique in the domain.
    3. Password does not meet domain requirements.
    4. -Path is not the Distinguished Name of a valid OU or container.
    5. -Name includes a character that must be escaped (with the backslash escape character "\"), such as one of the following:
    , \ # + < > ; " =
    The most common character that should be escaped is the comma.
    Richard Mueller - MVP Directory Services

  • Import CSV data to an existing populated XLS file

    Hi Guys,
    Looking for some assistance, with some powershell I have never done before..  and don't know where to start..
    I have a CSV file that contains some data - Several items exported from a standard powershell command.
    I also have an XLS file that has been manually populated for the last 6 months with data.
    What I want to get to (and have started with exporting the data to csv) is for the script to run, and add the data from the CSV to the XLS in the already exisiting colum heading.
    SO in the first row - we need to add the date, followed by adding data under each subsequent column that already has a heading..
    Anyone got any suggestions on where to start with this? Any advice greatly appreciated.
    Thanks
    Allan Harding

    I think your question is a bit too broad and vague.
    If you are not a scripter then I recommend asking in the Exxcel forum.  THey will help you learn how to use Excel tomerge data tables.
    If you want to scrpt this then youneed to start by learning how to write a script.  YOu will want to use Import-Csv and the Excel object model.
    If this is critical then I recommend contacting a consultant.
    http://technet.microsoft.com/en-us/scriptcenter/dd742419.aspx
    ¯\_(ツ)_/¯

  • Server is unwilling to process request with New-ADuser, Csv-Import.

    #>
    function Read-OpenFileDialog([string]$WindowTitle, [string]$InitialDirectory, [string]$Filter = "CSV (*.csv)|*.csv", [switch]$AllowMultiSelect)
    Add-Type -AssemblyName System.Windows.Forms
    $openFileDialog = New-Object System.Windows.Forms.OpenFileDialog
    $openFileDialog.Title = $WindowTitle
    if (![string]::IsNullOrWhiteSpace($InitialDirectory)) { $openFileDialog.InitialDirectory = $InitialDirectory }
    $openFileDialog.Filter = $Filter
    if ($AllowMultiSelect) { $openFileDialog.MultiSelect = $true }
    $openFileDialog.ShowHelp = $true # Without this line the ShowDialog() function may hang depending on system configuration and running from console vs. ISE.
    $openFileDialog.ShowDialog() > $null
    if ($AllowMultiSelect) { return $openFileDialog.Filenames } else { return $openFileDialog.Filename }
    $filePath = Read-OpenFileDialog -WindowTitle "Select CSV File" -InitialDirectory 'C:\Users\%USERNAME%' -Filter "Excel Spreadsheet (*.csv)|*.csv"
    if (![string]::IsNullOrEmpty($filePath)) { Write-Host "You selected the file: $filePath" }
    else { "You did not select a file." }
    Write-Host "This script will grab the path designated in the path column, make sure it is correct."
    Write-Host 'Press Enter to Continue...';
    Read-Host " "
    Import-Module ActiveDirectory
    Import-Csv $filePath | ForEach-Object{
    New-ADUser `
    -SamAccountName $_.sAMAccount`
    -Name $_.Name`
    -DisplayName $_.Name`
    -GivenName $_.cn`
    -SurName $_.sn`
    -Description $_.Description`
    -Department $_.Department`
    -EmailAddress $_.PrimaryEmail`
    -Path $_.Path`
    -AccountPassword (ConvertTo-SecureString -AsPlainText $_.Password -Force)`
    -Enabled $True `
    -PasswordNeverExpires $True `
    -HomeDirectory $_.HomeShare`
    -HomeDrive $_.HomeDrive`
    -ScriptPath $_.LogonScript`
    -PassThru `
    Here is my code, I know there are back ticks, dont hate .. I am getting a "server is unwilling to process request with New-ADuser. Am I needing another variable for the New-ADUser? Everything else works .

    Is this the correct format for path?
    >school.local
    ->ou-User Accounts
    --->ou-Students
    ------>ou-2015
    OU=User Accounts,OU=Students,OU=2015,DC=school,DC=local

  • PowerShell - Bulk-New-ADUser Creation via a csv file

    This script creates bulk AD users via a csv file. The script creates & configures the user accounts correctly even though the following error message appears. How can I correct this?
    Set-Locaiton : Cannot find path 'AD:Mydomain,OU=MyDomain,DC=My,DC=Domain,DC=org' because it does not exist.
    Import-Module ActiveDirectory
    $csv = Import-CSV -Path "C:\Temp\CreateUsers.csv"
    cd AD:
    set-location -path "OU=MyDomain,DC=My,DC=Domain,DC=org" -PassThru
    foreach($Item in $csv){
    $newUserID=@{
    Name=$item.userID
    Description=$item.description
    GivenName=$item.UserID
    surName=$item.UserID
    DisplayName=$item.UserID
    UserPrincipalName=$item.UserID + "@MyDomain.org"
    EmployeeID=$item.Owner
    ScriptPath="login.cmd"
    Try{
    New-ADUser @newUserID -ErrorAction Stop -AccountPassword (ConvertTo-SecureString $Item.Password -AsPlainText -Force) -PassThru
    Enable-ADAccount -Identity $item.userID
    Set-ADUser -Identity $item.userID -ChangePasswordAtLogon $true
    Write-Host "UserID $($item.UserID) created!" -ForegroundColor green
    Catch{
    Write-Host "There was a problem creating UserID $($item.UserID). The account was not created!" -ForegroundColor Red
    set-location -path "c:\temp"
    mamadukes

    Slight variation, populated from the AdventureWorks SQL database rather than a CSV
    Import-Module "SQLPS" -DisableNameChecking
    New-PSDrive -Name AWDB -PSProvider SQLServer -ROOT SQLSERVER:\sql\localhost\default\databases\adventureworks2012
    Set-Location AWDB:\Tables
    $SQLText = "SELECT e.BusinessEntityID, p.Title, p.FirstName, p.MiddleName, p.LastName, p.Suffix, "+
    "e.JobTitle, d.Name AS Department, d.GroupName, edh.StartDate, e.LoginID"+
    " FROM HumanResources.Employee AS e"+
    " INNER JOIN Person.Person AS p ON p.BusinessEntityID = e.BusinessEntityID"+
    " INNER JOIN HumanResources.EmployeeDepartmentHistory AS edh ON e.BusinessEntityID = edh.BusinessEntityID"+
    " INNER JOIN HumanResources.Department AS d ON edh.DepartmentID = d.DepartmentID"+
    " WHERE (edh.EndDate IS NULL)"+
    " AND (p.FirstName ='Brian')"
    $Query = Invoke-SQLCmd -Query $SQLText
    $Password = "P@assword1"
    foreach($Item in $Query)
    $LoginID=$Item.LoginID
    $LoginID="CORP\"+($LoginID).Substring(16)
    $newUserID=@{
    Name=$item.FirstName+$Item.LastName
    Description="This is a test of a bulk user add"
    GivenName=$item.FirstName
    Surname=$item.LastName
    DisplayName=$item.FirstName+" "+$Item.LastName
    UserPrincipalName="$($item.FirstName+"."+$Item.LastName)@corp.contoso.com"
    EmployeeID=$item.BusinessEntityID
    ScriptPath='login.cmd'
    Company="Contoso"
    Department=$Item.Department
    EmailAddress="$($item.FirstName+"."+$Item.LastName)@corp.contoso.com"
    Title=$Item.JobTitle
    $TargetOU="OU="+$item.Department+",DC=corp,DC=contoso,DC=com"
    Try{
    $newUserID
    New-ADUser @newUserID -Path $TargetOU -ErrorAction Stop -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Passthru
    Enable-ADAccount -Identity $newUserID.Name
    Set-ADUser -Identity $newUserID.Name -ChangePasswordAtLogon $true
    Write-Host "UserID $($newUserID.Name) created!" -ForegroundColor green
    Catch{
    Write-Host "There was a problem creating UserID $($item.UserID). The account was not created!" -ForegroundColor Red
    No need to be on the PSDrive AD:, the OU can be specified in the Path parameter in the New-ADUser.
    This was done on a member server with SQL Server (not a domain controller).
    Thanks for your help

Maybe you are looking for

  • MSI Big Bang-XPower II won't start.

    Bought the msi big bang xpower II and i can't get it to start... The power button is green so it is power there. Board: MSI Big Bang-XPower II VGA:  MSI GeForce GTX 780 Gaming 3GB PhysX PSU:  XFX ProSeries Black Edition 1250W Intel  Intel Core i7-482

  • Time Machine not working as supposed to.

    The other day i made changes that i wanted to "roll back". So i selected a date 1 day earlier and restored to that date. After the system rebooted it took the next 18 hours creating a new " image " in time machine. There was no way to stop this. Now

  • Apple sending mail to address not listed in my account

    [email protected] sent me emails to an account that i want to remove, but when I log into iCloud that address isn't listed there. Very confused and don't want to discard the address if apple thinks its active Any ideas? could there be somewhere else

  • So I went to install the latest Mac update but now it won't turn back on

    I Pressed the restart now button to install the latest update, the computer restarted then went to the apple logo with a progres bar. It went along for a few moments then just shut down. I tried to restart again but it just went back to the progress

  • Flex RIA FullScreen Application

    Hi,    i am creating an application in Flex.. when user open the this application i want open the flex in Fullscreen... Anybody can help me... already i tried but i have security error #2152 ...please help me Advance Thanks Kamal