Error running Powershell script from a .csv - powershell

I am trying to run a PowerShell script using the information contained within a .csv file.
My script is below:
Import-CSV \\chem-fp01\shared areas\IT\New IT Folder (Do Not Delete \\Powershell Scripts\Create New User.csv | ForEach-Object {
$Password = ConvertTo-SecureString $_.password -AsPlainText -Force
New-Mailbox -Name $_.Name
-FirstName $_.FirstName
-LastName $_.LastName
-Alias $_.Alias
-UserPrincipalName $_.UserPrincipalName
-Password $password
-ResetPasswordOnNextLogon $false
}
I am getting the error below and don't know what it means
Missing expression after unary operator '-'.
At C:\Scripts\CreateNewUser.psl:7 char:3
+ - <<<<LastName $_.LastName
+ CategoryInfo : ParserError: (-:String) [], ParseException
+ FullyQualifiedErrorId : MissingExpressionAfterOperator

You have to either, write all parameters to one line:
New-Mailbox -Name $_.Name -FirstName $_.FirstName -LastName $_.LastName -Alias $_.Alias -UserPrincipalName $_.UserPrincipalName -Password $password -ResetPasswordOnNextLogon $false
Or you can use splatting (Thanks Frode F.):
$parameters = #{
Name = $_.Name
FirstName = $_.FirstName
LastName = $_.LastName
Alias = $_.Alias
UserPrincipalName = $_.UserPrincipalName
Password = $password
ResetPasswordOnNextLogon = $false
}
New-Mailbox #parameters
Another solution would be to use the ` character at the end of the line (not recommended) :
New-Mailbox -Name $_.Name `
-FirstName $_.FirstName `
-LastName $_.LastName `
-Alias $_.Alias `
-UserPrincipalName $_.UserPrincipalName `
-Password $password `
-ResetPasswordOnNextLogon $false

The reason this command fails, is because your CSV file path contains spaces, and you are not surrounding it with double or single quotes.
Whenever your path contains blank spaces, just add quotes at the beginning and end of the path like this:
Import-CSV "\\chem-fp01\shared areas\IT\New IT Folder (Do Not Delete \\Powershell Scripts\Create New User.csv"

Related

How to resolve NewAD error with -Path $OU

I am currently trying to automate the creation of new users on my Active Directory.
However when I run my powershell here is the error that presents itself to me :
New-ADUser: Unable to validate argument on "Path" parameter. The argument is null or empty. Provide an argument that is not null or empty and try again.
At character Line: 23:19
+ -Path $ OR `
+ ~~~
+ CategoryInfo: InvalidData: (:) [New-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId: ParameterArgumentValidationError, Microsoft.ActiveDirectory.Management.Commands.NewADUser
What can i do ?
Thanks for your help !
This is my code
$ADUsers = Import-csv E:\SCRIPT\newusers.csv
foreach ($User in $ADUsers)
{
$Username = $User.username
$Password = $User.password
$Firstname = $User.firstname
$Lastname = $User.lastname
$Description = $User.description
$OU = $User.ou
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Lastname#domaine.fr" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-ChangePasswordAtLogon $False `
-DisplayName "$Lastname, $Firstname" `
-Description $Description `
-AccountPassword $Password `
-Path $OU `
}
Your comment indicates the CSV file uses the ; semi-colon as delimiter character, but you neglect to add that to the Import-Csv cmdlet. Now it is trying to parse the data using the default comma , and because of that none of the fields have a correct value.
Replace the first line with
$ADUsers = Import-csv -Path 'E:\SCRIPT\newusers.csv' -Delimiter ';'
Other than that, have a look at using splatting, so you don't need those awkward backticks.

add AD account with custom attribute using powershell

I am trying to add an account using powershell along with a cutom attribute. Schema extension is done and from attribute editor i can see that value of custom attribute "test" is not set.
$pw = "jakdakjdJAKJKA123";
$spw = ConvertTo-SecureString $pw -AsPlainText -force;
$accountname = "mytest";
$des = "Description";
$otherAttributes = #{'test' = "testval"};
New-AdUser -UserPrincipalName "$accountname#testdomain.local" -path "OU=Services,OU=Users,OU=OrgA,DC=testdomain,DC=local" -Name "$accountname" -SamAccountName "$accountname" -GivenName "$accountname" -Description $des -CannotChangePassword $true -DisplayName "$accountname" -PasswordNeverExpires $true -AccountPassword $spw -Enabled $true -otherAttributes $otherAttributes
when i run above code i get an error.
New-AdUser : The parameter is incorrect
At line:6 char:1
+ New-AdUser -UserPrincipalName "$accountname#testdomain.local" -path "OU=S ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (CN=mytest...testdomain,DC=local:String) [New-ADUser], ADInvalidOperationException
+ FullyQualifiedErrorId : ActiveDirectoryServer:87,Microsoft.ActiveDirectory.Management.Commands.NewADUser
if i remove "-otherAttributes $otherAttributes", account will be added successfully.
Question is how can i add account with custom attribute?
Take the email out of the UserPrincipalName
New-AdUser -UserPrincipalName "$accountname" -path "OU=Services,OU=Users,OU=OrgA,DC=testdomain,DC=local" -Name "$accountname" -SamAccountName "$accountname" -GivenName "$accountname" -Description $des -CannotChangePassword $true -DisplayName "$accountname" -PasswordNeverExpires $true -AccountPassword $spw -Enabled $true -otherAttributes $otherAttributes

can't create userS via powershell

I can't import users in powershell with a script via an csv file, but If I print the parameters on the screen,it shows them as it should.
what I am doing wrong? in my life plenty with that mustache, but plis focus on the script.
is running windows server 2016 on the powershell ise, on virtualbox
The Script:
If(-Not(Get-ADOrganizationalUnit -Filter {Name -eq "991-5D"}))
{New-ADOrganizationalUnit "991-5D" -Path (Get-ADDomain).DistinguishedName}
If(-Not(Get-ADOrganizationalUnit -Filter {Name -eq "911-5V"}))
{New-ADOrganizationalUnit "911-5V" -Path (Get-ADDomain).DistinguishedName}
$domain=(Get-ADDomain).DNSRoot
Import-Csv -Path "C:\Alumnos.csv" | foreach-object {
[int]$number= $_.X
If($number -ge 10 -and $number -le 26)
{
$UO="991-5D"
}
//there are many others O.U.
$ou= "UO="+$UO+","+$domain
$UPN = $_.LETRA+$_.PATERNO+$_.X+"#"+ "$domain"
$CUENTA= $_.LETRA+$_.PATERNO+$_.X
New-ADUser -SamAccountName $CUENTA -UserPrincipalName $CUENTA -Name $_.NOMBRE
-SurName $_.PATERNO -GivenName $_.NOMBRE -EmailAddress $UPN -AccountPassword
(ConvertTo-SecureString "Leica666" -AsPlainText -force) -Path $ou
-Enabled $true -ChangePasswordAtLogon $true -Verbose}
the data:
X,PATERNO,MATERNO,NOMBRE,SEGUNDO,LETRA
10,ARÉVALO,CORNEJO,NICOLÁS,ALEJANDRO,N
11,BARRIOS,MONTERO,BENJAMÍN,IGNACIO,B
12,BUSTAMANTE,LOYOLA,IGNACIO,HERNANDO,I
13,BUSTOS,GARRIDO,ARTURO,IGNACIO,A
this are the results on each line:
+ New-ADUser -SamAccountName $CUENTA -UserPrincipalName $CUENTA -Name $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo:NotSpecified: (CN=IGNACIO,UO=9...da.com:String)
[New-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8335,
Microsoft.ActiveDirectory.Management.Commands.NewADUser
the head:
X,PATERNO,MATERNO,NOMBRE,SEGUNDO,LETRA
echo:
#{X=42; PATERNO=PAYACÁN; MATERNO=ZAPATA; NOMBRE=NICOLÁS; SEGUNDO=N; LETRA=}.NOMBRE
I know that reads the file and instead of reading just the column reads all the line($_), and then prints whatever I wrote next to it(".name", ".section", etc).
I've made some variable and format changes to make this code more successful.
$domain=Get-ADDomain
Import-Csv -Path "C:\Alumnos.csv" |
Foreach-Object {
[int]$number= $_.X
If($number -ge 10 -and $number -le 26)
{
$UO="991-5D"
}
$ou = "OU={0},{1}" -f $UO,$domain.DistinguishedName
$UPN = "{0}{1}{2}#{3}" -f $_.LETRA,$_.PATERNO,$_.X,$domain.DNSRoot
$CUENTA= "{0}{1}{2}" -f $_.LETRA,$_.PATERNO,$_.X
New-ADUser -SamAccountName $CUENTA -UserPrincipalName $UPN -Name $_.NOMBRE `
-SurName $_.PATERNO -GivenName $_.NOMBRE -EmailAddress $UPN `
-AccountPassword (ConvertTo-SecureString "Leica666" -AsPlainText -force) -Path $ou `
-Enabled $true -ChangePasswordAtLogon $true -Verbose
}
Explanation:
$domain: I've made this an ADDomain object. This allows the DistinguishedName and DNSRoot properties to be accessed where appropriate.
-f operator: I used the format operator to make it easier to read the string concatenation attempts.
$ou: This is constructed using the DistinguishedName of the domain. This is the proper format for the OU path.
$UPN: This is constructed using the DNSRoot of the domain. It can obviously be different than your domain, but must be in an email address or FQDN format.
Additional Comments:
You are setting -Name to be $_.NOMBRE. This could be problematic because Name must be unique in each OU. Name is used to build the CN, which is where uniqueness is required. If you have NICOLAS in OU 991-5D, you are going to get an error if you try to create another NICOLAS in the same place. IMHO, I would do something different. You could also implement the use of splatting for building the properties of your New-ADUser command, but that is only for readability purposes. Below is an example of splatting:
$NewUserProperties = #{
SamAccountName = $CUENTA
UserPrincipalName = $UPN
Name = $_.NOMBRE
Surname = $_.PATERNO
GivenName = $_.NOMBRE
EmailAddress = $UPN
AccountPassword = (ConvertTo-SecureString "Leica666" -AsPlainText -force)
Path = $ou
Enabled = $true
ChangePasswordAtLogon = $true
}
New-ADUser #NewUserProperties -Verbose

ADSI not validating correctly?

I have a CSV with 1500+ users there are 30 users per class OU, and then 6 class OU's per Intake OU. What I'm trying to achieve is, foreach (user in CSV), check if OU exists, then check if parent OU exists, create the parent OU only if it doesn't exist, then create the OU, then create the user, or just create the user if the OU exists.
Here is the code I'm using:
$ErrorActionPreference = "Stop"
Import-Module ActiveDirectory
$CSV = Import-Csv "C:\Scripts\AddPupils.csv"
foreach ($user in $CSV) {
# Variables
$GivenName = $user.GivenName
$SurName = $user.SurName
$UserName = $user.UserName
$Class = $user.YearClass
$Intake = $user.Intake
$DisplayName = $GivenName+" "+$SurName
# Create User
$UserOUParent = "OU=Year "+$iIntake+" Intake,OU=Students,OU=Users,OU=Roding,DC=Zulbag,DC=com"
$UserOU = "OU=Class "+$Class.Substring(1,1)+",OU=Year "+$iIntake+" Intake,OU=Students,OU=Users,OU=Roding,DC=Zulbag,DC=com"
$NewUserOUParentCheck = [ADSI]::Exists("LDAP://$UserOUParent")
$NewUserOUCheck = [ADSI]::Exists("LDAP://$UserOU")
if ($NewUserOUCheck -eq $false){
if ($NewUserOUParentCheck -eq $false){
"Create Parent Ou"
New-ADOrganizationalUnit `
-Name ("Year "+$Intake+" Intake") `
-Path "OU=Students,OU=Users,OU=Roding,DC=Zulbag,DC=Com" `
-ProtectedFromAccidentalDeletion $False
}
"Create OU"
New-ADOrganizationalUnit `
-Name ("Class "+$Class.Substring(1,1)) `
-Path ("OU=Year "+$Intake+" Intake,OU=Students,OU=Users,OU=Roding,DC=Zulbag,DC=Com") `
-ProtectedFromAccidentalDeletion $False
}
"Create User"
New-ADUser `
-Name $DisplayName `
-SurName $SurName `
-GivenName $GivenName `
-DisplayName $DisplayName `
-SamAccountName $UserName `
-UserPrincipalName ($UserName+"#Zulbag.com") `
-AccountPassword (ConvertTo-SecureString "Testing123" -AsPlainText -force) `
-CannotChangePassword $true `
-ChangePasswordAtLogon $false `
-PasswordNeverExpires $true `
-EmailAddress ($UserName+"#Zulbag.com") `
-Country "GB" `
-Path ("OU=Class "+$Class.Substring(1,1)+",OU=Year "+$Intake+" Intake,OU=Students,OU=Users,OU=Roding,DC=Zulbag,DC=Com") `
-ProfilePath ("D:\Shares\User Accounts\Students\Intake Year "+$Intake+"\Class "+$Class.Substring(1,1)+"\Profiles\"+$DisplayName) `
-Enabled $true
Start-Sleep -Seconds 5
# Add To Group
$Group = "CN=Redirection "+$Intake.Substring(2,2)+$Class.Substring(1,1)+",OU=Intake "+$Intake+",OU=Security Groups,OU=Roding,DC=Zulbag,DC=Com"
$GroupOU = "OU=Intake "+$Intake+",OU=Folder Redirection Groups,OU=Security Groups,OU=Roding,DC=Zulbag,DC=Com"
$NewGroupCheck = [ADSI]::Exists("LDAP://$Group")
$NewGroupOUCheck = [ADSI]::Exists("LDAP://$GroupOU")
if ($NewGroupCheck -eq $false) {
if ($NewGroupOUCheck -eq $false) {
"Create OU"
New-ADOrganizationalUnit `
-Name ("Intake "+$Intake) `
-Path "OU=Folder Redirection Groups,OU=Security Groups,OU=Roding,DC=Zulbag,DC=Com" `
-ProtectedFromAccidentalDeletion $False
}
"create Group"
New-ADGroup `
-Name ("Redirection "+$Intake.Substring(2,2)+$Class.Substring(1,1)) `
-GroupScope "Global" `
-Path ("OU=Intake "+$Intake+",OU=Folder Redirection Groups,OU=Security Groups,OU=Roding,DC=Zulbag,DC=Com")
}
"Add Member"
Add-ADGroupMember ("Redirection "+$Intake.Substring(2,2)+$Class.Substring(1,1)) $UserName
}
pause
Sample CSV:
GivenName,SurName,Class,UserName,Intake
Ali,Grisdale,1B,AGris,2016
Ayomiposi,Olayera,1B,AOlay,2016
In tests with Write-Output, the [ADSI] validates correctly but it appears to be validating it incorrectly here, the error message I keep getting is:
New-ADOrganizationalUnit : An attempt was made to add an object to the
directory with a name that is already in use
At C:\Scripts\AddPupils-Afzal.ps1:24 char:13
+ New-ADOrganizationalUnit
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (OU=Year 2016 In...C=Zulbag,DC=Com:String) [New-ADOrganizationalUnit], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8305,Microsoft.ActiveDirectory.Management.Commands.NewADOrganizationalUnitdirectory
It successfully creates the parent OU, class OU and user, but fails to create the second user, instead validates the OU incorrectly again.
Any Ideas?
Check the script for path errors!

New-Aduser : The object name has bad syntax

I have a script which i use to create bulk users from a csv file which works fine.
Import-Csv e:\temp\newemps.csv | %{
$ou = $_.ou
$firstname = $_.first
$lastName = $_.last
$accountName = $("{0}{1}" -f $firstname.Substring(0,1),$lastName).ToLower()
$description = $_.desc
$password = "Welcome1"
$name = "$firstName $lastName"
New-AdUser -SamAccountName $accountName -GivenName $firstName -UserPrincipalName "$accountName#ba.net" -Surname $lastName -DisplayName $name -Name $name -AccountPassword (ConvertTo-SecureString -AsPlainText $password -Force) -Enabled $true -Path $ou -Description $description -ChangePasswordAtLogon:$False
If ($_.Group -ne ""){
Add-adgroupmember -identity $_.group -members $accountName
}
If ($_.email -eq "y"){
Enable-Mailbox -Identity $accountName -Alias $accountName
Set-Mailbox $accountName -MaxSendSize 10mb -MaxReceiveSize 10mb
Get-CasMailbox $accountName -OwaEnabled:$false -ActiveSyncEnabled:$false
}
}
I was trying modify this script so that i could create some generic accounts that would not follow our typical convention. The input is a here-string as supposed to a csv as the only unique item is an Airport code. I have shortened the here-string for brevity.
$bases = #"
YAB
YEK
YYH
YHI
"#
$bases.Split("`n") | %{
$ou = "CN=Users,DC=BA,DC=NET"
$firstname = "$_".ToString()
$lastName = "Counter"
$accountName = "$_" + "Counter"
$description = "Base Front Counter"
$password = "Welcome1"
$name = "$firstName $lastName"
New-AdUser -SamAccountName $accountName -GivenName $firstName -UserPrincipalName "$accountName#ba.net" -Surname $lastName -DisplayName $name -Name $name -AccountPassword (ConvertTo-SecureString -AsPlainText $password -Force) -Enabled $true -Path $ou -Description $description -ChangePasswordAtLogon:$False
}
There is something about using a here-string that I am not accounting for. The only account it successfully creates is the one for YHI (The last one of the here-string). For all others it gives New-AdUser : The object name has bad syntax. Internet research shows many errors for csv-imports where the data has whitespace and other issues there but im not sure what the issue is here.
In the end I just made a csv file instead of using the here-string but I would like to know what i was doing wrong.
This worked for me. got rid of the null values and the new line values and just gave me each string value from each line. Seams there may have been some white space or some other characters that interfere if you just do split "`n"
$test = #"
user1
user2
user3
"#
$test.split(“`r`n”) | ForEach-Object {if($_){get-aduser $_}}