Bulk Add AD through Powershell/CSV issue - powershell

I am trying to bulk-add users into my Active Directory, but I am getting expression errors right at the start of the script. I am not a script buff at all, so I am really out of ideas from the get go.
$Users = Import-Csv ".\UsersFile.csv"
foreach ($User in $Users)
{
-OrganizationalUnit $User.OU
-SamAccountName $User.UserName
-userPassword $User.Password
-GivenName $User.First
-Initials $USer.Initial
-sn $User.Last
-Displayname $User.DisplayName
-Description $User.Description
-Physicaldeliveryofficename $User.Office
-TelephoneNumber $User.Tel
-Mail $User.mail
-streetaddress $User.Street
-postOfficeBox $User.Postbus
-l $User.Location
-st $User.Provincie
-postalCode $User.Postcode
-c $User.Land
-deparment $User.Department
-Company $User.Organisatie
-Manager $User.Manager
-Password $User.Password -ResetPasswordOnNextLogon $false
}
The error log.
Missing expression after unary operator '-'.
At C:\Users\Administrator\Desktop\CreateUserBulk.ps1:4 char:10
+ - <<<< OrganizationalUnit $User.OU `
+ CategoryInfo : ParserError: (-:String) [], Parseexception
+ FullyQualifiedErrorID : MissingExpressionAfterOperator
After trying the link (From serv) and editing the CSV and script accordingly, getting a lot more errors now with this.
Import-Csv : Cannot open file "C:\Users\administrator\UsersFile.csv".
At C:\Users\administrator\Desktop\Untitled3.ps1:2 char:20
+ $Users = Import-Csv <<<< -Delimiter ";" -Path ".\UsersFile.csv"
+ CategoryInfo : OpenError: (:) [Import-Csv], FileNotFoundException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.ImportCsvCommand
You cannot call a method on a null-valued expression.
At C:\Users\administrator\Desktop\Untitled3.ps1:9 char:53
+ $FirstLetterFirstname = $UserFirstname.substring <<<< (0,1)
+ CategoryInfo : InvalidOperation: (substring:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
ConvertTo-SecureString : Cannot bind argument to parameter 'String' because it is null.
At C:\Users\administrator\Desktop\Untitled3.ps1:11 char:195
+ New-ADUser -Name $Detailedname -SamAccountName $SAM -UserPrincipalName $SAM -DisplayName $Detailedname -GivenName
$user.firstname -Surname $user.name -AccountPassword (ConvertTo-SecureString <<<< $Password -AsPlainText -Force) -Ena
bled $true -Path $OU
+ CategoryInfo : InvalidData: (:) [ConvertTo-SecureString], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertToSe
cureStringCommand
EDIT2: Fixed, I changed the source link to it's fullness and now it works!

You are not creating a new AD user in your script. So -OrganizationalUnit should be undefined and throw an error, excpet you declare them as a variable first.
Import-Module ActiveDirectory
$Users = Import-Csv -Delimiter ";" -Path ".\UsersFile.csv"
foreach ($User in $Users)
{
$FirstLetterFirstname = $User.firstname.substring(0,1)
New-ADUser -Name $User.firstname + " " + $User.name
-SamAccountName $FirstLetterFirstName + $User.name
//... and so on
}
You can declare all variables first in the manner of $FirstletterFirstName and execute the New-ADUser command at the end of each loop, which makes it easier to read and modify later on.
The important part stays: Adding a new user is executed through the New-ADUser command which you are missing. You can also add the New-ADUser to the top of your loop, which should make your query work if there are no other syntax errors / Spelling errors in your code
//EDIT: You can find a working example at http://gallery.technet.microsoft.com/scriptcenter/ed20b349-9758-4c70-adc0-19c5acfcae45
and the TechNet article for New-ADUser:
http://technet.microsoft.com/en-us/library/ee617253.aspx

Related

In windows powershell ISE, trying to bulk update people information. I get this error message

I'm trying to bulk update people information. I get this error message.
The users2.csv file contains this:
UserPrincipalName,Company,CountryOrRegion,DisplayName,Fax,FirstName,Initials,LastName,MobilePhone,Phone,Title,WindowsEmailAddress,Name
test#bio-dynamics.be,Bio-Dynamics,Belgium,Test,Test,Test,Test,Test,Test,Test,Test,test#bio-dynamics.be,Test
test2#bio-dynamics.be,Bio-Dynamics,France,Test2,Test2,Test2,Test2,Test2,Test2,Test2,Test2,test2#bio-dynamics.be,Test2
The error message is this:
PS C:\WINDOWS\system32> Import-Csv "c:\scripts\users2.csv" | ForEach {Set-user UserPrincipalName $_.UserPrincipalName -Company $_.company -CountryOrRegion $_.CountryOrRegion -DisplayName $_.DisplayName -Fax $_.Fax -FirstName $_.FirstName -Initials $_.Initials -LastName $_.LastName -MobilePhone $_.MobilePhone -Phone $_.Phone -Title $_.Title -WindowsEmailAddress $_.WindowsEmailAddress -Name $_.Name}
A positional parameter cannot be found that accepts argument 'test#bio-dynamics.be'.
+ CategoryInfo : InvalidArgument: (:) [Set-User], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Set-User
+ PSComputerName : outlook.office365.com
A positional parameter cannot be found that accepts argument 'test2#bio-dynamics.be'.
+ CategoryInfo : InvalidArgument: (:) [Set-User], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Set-User
+ PSComputerName : outlook.office365.com
Can anybody help point me toward the problem? Thank you so much!

Add ProxyAddresses to separate script

Goal: Append script to add three different SMTP addresses.
Script: https://thesysadminchannel.com/how-to-create-o365-mailboxes-hybrid-exchange/
Code Snippet:
Write-Host "Continuing will create the AD account and O365 Email." -ForegroundColor:Green
Write-Host
$Proceed = $null
$Proceed = Read-Host "Continue? (y/n)"
if ($Proceed -ieq 'y') {
Write-Host "Creating the O365 mailbox and AD Account."
New-RemoteMailbox -Name $fullname -FirstName $firstname -LastName $lastname -DisplayName
$fullname -SamAccountName $logonname -UserPrincipalName $logonname#$domain -PrimarySmtpAddress
$logonname#$domain -Password $password -OnPremisesOrganizationalUnit $OU -DomainController $Server
Write-Host "Done..."
Write-Host
Write-Host
Sleep 5
Write-Host "Adding Properties to the new user account."
Get-ADUser $logonname -Server $Server | Set-ADUser -Server $Server -Description $Description -
Office $Office -StreetAddress $StreetAddress -City $City -State $State -PostalCode $PostalCode -
Country $Country -Title $Title -Department $Department -Company $Company -Manager $Manager -
EmployeeID
$EmployeeID
Write-Host "Done..."
Write-Host
Write-Host
if ($MemberOf) {
Write-Host "Adding Membership Groups to the new user account."
Get-ADUser $logonname -Server $Server | Add-ADPrincipalGroupMembership -Server $Server -
MemberOf $MemberOf
Write-Host "Done..."
Write-Host
Write-Host
}
}
Get-PSSession | Remove-PSSession
What I'm trying to add are these three values:
SMTP:user#domain.com
smtp:user#domain.mail.onmicrosoft.com
smtp:user#domain.onmicrosoft.com
This is along the lines of what I've come up with:
Write-Host "Adding Properties to the new user account."
Get-ADUser $logonname -Server $Server | Set-ADUser -Server $Server -Description $Description
-Office $Office -StreetAddress $StreetAddress -City $City -State $State -PostalCode $PostalCode -
Country $Country -Title $Title -Department $Department -Company $Company -Manager $Manager -
EmployeeID $EmployeeID
Write-Host "Done..."
Write-Host
Write-Host
Write-Host “Setting up TCS E-mail Standard”
$userinfo.ProxyAddresses = "SMTP:" + ($FirstInitial.Add(1)) + ($userinfo.sn) +
"#DOMAIN.COM"
#$userinfo.ProxyAddresses += "smtp:" + ($userinfo.givenname) + "." + ($userinfo.sn) +
"#domain.mail.onmicrosoft.com"
$userinfo.ProxyAddresses += "smtp:" + ($FirstInitial.Remove(1)) + ($userinfo.sn) +
"#domain.onmicrosoft.com"
$userinfo.targetAddress = "SMTP:" + ($userinfo.sAMAccountName) +
"#domain.mail.onmicrosoft.com"
Write-Host "Done..."
Write-Host
Then I get this error:
You cannot call a method on a null-valued expression.
At C:\Users\Temp\CreateStudentEmail.ps1:233 char:21
+ ... $userinfo.ProxyAddresses = "SMTP:" + ($FirstInitial.Add(1 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Users\Temp\CreateStudentEmail.ps1:235 char:21
+ ... $userinfo.ProxyAddresses += "smtp:" + ($FirstInitial.Rem ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
The property 'targetAddress' cannot be found on this object. Verify that the property exists and can
be set.
At C:\Users\Temp\CreateStudentEmail.ps1:236 char:21
+ ... $userinfo.targetAddress = "SMTP:" + ($userinfo.sAMAccou ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
Just trying to find a way to incorporate the proxy address section so that I don't have to worry about extra steps.
I pulled the code from another PowerShell I used years ago, then tweaked it a bit, but it DOES actually input SMTP address fields into the AD character. It still throws errors though.
Here is what you need to do:
set-Aduser $samaccountname -Add #{ proxyAddresses = "SMTP:user#domain.com","smtp:user#domain.mail.onmicrosoft.com","smtp:user#domain.onmicrosoft.com" }

Adding users via powershell script gives error

I am trying to ad users from a csv file to an OU with a powershell script but getting some error?
I'll post the line that I am using for adding the users. And I have checked that the retrieval path for the csv file is correct..
New-ADUser -SamAccountName $login -Name $namn -GivenName $Fname -Surname $Enamn -Department $user.Department -Division $user.Division -Title $user.role -Description $user.Extension -Office $user.Office -UserPrincipalName $login"#hqad.local" -path "OU=Carb_users,DC=HQAD,DC=Local" -EmailAddress $mail -AccountPassword (ConvertTo-SecureString -AsPlainText "Syp9393" -Force) -Enable $True
Error output:
New-ADUser : The server is unwilling to process the request
At C:\Users\Administrator\Desktop\Userscript.ps1:37 char:1
+ New-ADUser -SamAccountName $login -Name $namn -GivenName $Fname -Surn ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=Carl Malm,OU...C=HQAD,DC=Local:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.NewADUser
Happy for any help!

Add users to Active Directory

I'm trying to use the script below to add new users to Active Direcroty but for some reason I keep gettings error messages:
The Script:
Import-Module ActiveDirectory
Import-Csv 'C:\Scripts\\AddUsers.csv' -Delimiter "," | ForEach-Object {
$userPrincinpal = $_."SAM" + "#domain.org"
New-ADUser
-Name $_.Name `
-GivenName $_."First_Name" `
-Surname $_."Last_Nimpoame" `
-Description "Student"
-Path $_."OU" `
-SamAccountName $_."SAM" `
-UserPrincipalName $userPrincinpal `
-AccountPassword (ConvertTo-SecureString "password2016" -AsPlainText -Force) `
-ChangePasswordAtLogon $true `
-Enabled $true
}
Write-Host "Done!"
The error message:
-Name : The term '-Name' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included,
verify that the path is correct and try again.
At C:\Scripts\Add Bulk AD User CSV\add_ad_users2.ps1:5 char:2
+ -Name $_.Name `
+ ~~~~~
+ CategoryInfo : ObjectNotFound: (-Name:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
-Path : The term '-Path' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included,
verify that the path is correct and try again.
At C:\Scripts\Add Bulk AD User CSV\add_ad_users2.ps1:9 char:2
+ -Path $_."OU" `
+ ~~~~~
+ CategoryInfo : ObjectNotFound: (-Path:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
I'm not sure why I keep getting those error messages since I already imported the ActiveDirectory Module.
Can you please help?!
You are missing a trailing backtick after the New-ADUser:
Import-Module ActiveDirectory
Import-Csv 'C:\Scripts\\AddUsers.csv' -Delimiter "," | ForEach-Object {
$userPrincinpal = $_."SAM" + "#domain.org"
New-ADUser `
-Name $_.Name `
-GivenName $_."First_Name" `
-Surname $_."Last_Nimpoame" `
-Description "Student"
-Path $_."OU" `
-SamAccountName $_."SAM" `
-UserPrincipalName $userPrincinpal `
-AccountPassword (ConvertTo-SecureString "password2016" -AsPlainText -Force) `
-ChangePasswordAtLogon $true `
-Enabled $true
}
Write-Host "Done!"

Importing users from CSV into AD with PowerShell

I'm using the following script in order to import 100,000 users from a CSV file into Active Directory. However, I'm getting a lot of errors and need your help in eliminating them.
Script:
Import-Csv C:\csv\100Kusers.csv | ForEach-Object {
$userPrinc = $_."Logon Username" + "#mydomain.com"
New-QADUser -Name $_.Name `
-ParentContainer $_."Container" `
-SamAccountName $_."Logon Username" `
-UserPassword "passw0rd123" `
-FirstName $_.FirstName `
-LastName $_."LastName" `
-Description $_."Department" `
-UserPrincipalName $userPrinc `
-DisplayName $_."Name" `
-StreetAddress $_."StreetAddress" `
-City $_."City" `
-State $_."State" `
-PostalCode $_."PostalCode" `
-Email $_."Email" `
-Company $_."Company" `
-Department $_."Department" `
-HomePhone $_."HomePhone" `
-Title $_."Title" `
-Manager $_."Manager" ;`
Add-QADGroupMember -identity $_."Group" -Member $_."Logon Username" ;`
}
And here are the errors I'm getting:
Add-QADGroupMember : Cannot resolve directory object for the given identity: 'jm?lmhx4'.
At C:\csv\PS_import_script.ps1:22 char:2
+ Add-QADGroupMember -identity $_."Group" -Member $_."Logon Username" ;`
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Add-QADGroupMember], ObjectNotFoundException
+ FullyQualifiedErrorId : Quest.ActiveRoles.ArsPowerShellSnapIn.DirectoryAccess.ObjectNotFoundException,Qu
est.ActiveRoles.ArsPowerShellSnapIn.Commands.AddGroupMemberCmdlet2
New-QADUser : A device attached to the system is not functioning.
At C:\csv\PS_import_script.ps1:3 char:2
+ New-QADUser -Name $_.Name `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-QADUser], DirectoryServicesCOMException
+ FullyQualifiedErrorId : System.DirectoryServices.DirectoryServicesCOMException,Quest.ActiveRoles.ArsPowerShellSnapIn.Powershell.Cmdlets.NewUserCmdlet
CSV looks like this:
FirstName Surname Name StreetAddress City State PostalCode EmailAddress Company Department Group HomePhone Title Manager Logon Username Container
Jose Mullane Jose Mul Rue de Li?ge 493 Lompret WLX 6463 JoseLMullane#superrito.com rmit QA QA-FL 0495 94 79 62 Laboratory animal technologist tgatesjr jmuljhk2 dcui.mydomain.com/dcui_OU/Finland/Departments/QA
Sorry, can't add more - formatting goes crazy when I copy a plain CSV into the post window.
Many thanks everyone. I agree that this could be an encoding issue and yes, the CSV itself had all those off "?" marks, after I saved it from xlsx format. We ended up using Pyhthon, which also was much faster, comparing to Pshell.
Yours,