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" }
Related
I'm quite new to PowerShell and still at entry-level. I'm running into an issue with my script and hope to seek some help here.
The objective I wanted to achieve is:
Create new users from .csv where their attribute values are filled
bases on their jobtitle: Add different groups, move the user to different OU
My script did work with user account creation and adding groups, but after I added the OU moving part, it failed. I'm attaching my script here and the error message, any advice would be really really helpful!!
Thank you very much in advance.
Import-Module activedirectory
$ADUsers = Import-csv 'D:\OneDrive - testit\IT Dept\PowerShell\Scripts\Case_Study\New_Employee_Action\RA_Test3.csv'
foreach ($User in $ADUsers)
{
$Lastname = $User.EnglishLastName
$Firstname = $User.EnglishFirstName
$department = $User.Department
$Username = $User.Account
$Password = $User.Password
$email = $User.Email
$displayname= $User.Displayname
$employeeid = $User.EmployeeID
$employeenumber = $User.EmployeeNumber
$OU = "OU=Rachel test,OU=Users,OU=testit,DC=testit,DC=edu,DC=cn"
$city = $User.city
$zipcode = $User.Zipcode
$jobtitle = $User.JobTitle
$company = $User.Company
$employeeType = $User.employeeType
if (Get-ADUser -F {SamAccountName -eq $Username})
{
Write-Warning "A user account with username $Username already exists in Active Directory."
}
else
{
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Username#testit.edu.cn" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-DisplayName "$displayname" `
-Path $OU `
-EmployeeID $employeeid `
-EmployeeNumber $employeenumber `
-City $city `
-PostalCode $zipcode `
-Title $jobtitle `
-Company $company `
-Department $department `
-EmailAddress $email `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $True `
-OtherAttributes #{'employeeType'=$employeeType}
}
$RA_Groups = #("Chinese Staff","$testStaffUsers","testUsers","Research Assistants")
$OU_RA = "OU=Research Assistant,OU=Academic,OU=Staff,OU=Users,OU=testit,DC=testit,DC=edu,DC=cn"
ForEach ($ADUser in $ADUsers)
{
if($jobtitle -eq 'Research Fellow (RF)'){
foreach($RA_Group in $RA_Groups){
Add-ADGroupMember -Identity $RA_Group -Members $Username
}
Move-ADObject -Identity $Username -TargetPath $OU_RA
Write-Output "Moved Account $($Username) to $($OU_RA)"
Write-Output "User $($Username) has been added to group $($RA_Groups)"
}
}
}
Add-ADGroupMember : Cannot find an object with identity: '' under: 'DC=testit,DC=edu,DC=cn'.
At D:\OneDrive - testIT\IT Dept\PowerShell\Scripts\Case_Study\New_Employee_Action\New_Employee_test.ps1:88 char:17
+ ... Add-ADGroupMember -Identity $RA_Group -Members $Username
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:ADGroup) [Add-ADGroupMember], ADIdentityNotFoundException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember
Move-ADObject : Cannot find an object with identity: 'test.RA' under: 'DC=testit,DC=edu,DC=cn'.
At D:\OneDrive - testit\IT Dept\PowerShell\Scripts\Case_Study\New_Employee_Action\New_Employee_test.ps1:90 char:13
+ Move-ADObject -Identity $Username -TargetPath $OU_RA
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (test.RA:ADObject) [Move-ADObject], ADIdentityNotFoundException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.MoveADObject
Moved Account test.RA to OU=Research Assistant,OU=Academic,OU=Staff,OU=Users,OU=testit,DC=testit,DC=edu,DC=cn
User test.RA has been added to group Chinese Staff testUsers Research Assistants
There seem to be two problems here:
Move-ADObject : Cannot find an object with identity: 'test.RA'
Move-ADObject does not take the samaccountname as an input - the documentation indicates it wants either a distinguished name or a GUID. To solve this, once you have created the account, you can either Get-ADUser the username (to get the GUID / DN) or bodgy it up using your already known values from the script - I'd recommend using Get-ADUser for simplicity
$dn = Get-ADUser $username | Select-Object -expand DistinguishedName
Move-ADObject -Identity $dn -TargetPath $OU_RA
Add-ADGroupMember : Cannot find an object with identity: ''
You've defined the groups with names, but one is defined as a variable instead - it's likely here you're experiencing the error. You can see in the below that $testStaffUsers is a variable (identified by the $). Removing the $, or ensuring the variable is defined, would resolve the problem.
$RA_Groups = #("Chinese Staff","$testStaffUsers","testUsers","Research Assistants")
would become
$RA_Groups = #("Chinese Staff","testStaffUsers","testUsers","Research Assistants")
I am creating a script to create users on a domain for one of my clients (NHS in the UK), however it currently refuses to create the AD User & exchange account if the user has a First & Second Name that Already Exists within the AD.
I have already bypassed username duplication by adding a number onto the end of the usernames if they already exist. However, if the first / second name is duplicated it will not create the account.
$DisplayName = $Surname + " " + $GivenName
$Mail = $GivenName + "." + $Surname + "#" + "royalberkshire.nhs.uk"
$MailAlias = $GivenName + "." + $Surname + "#" + $DNSRoot2
$SInitial = $Surname[0]
$Initial = $GivenName[0]
$SAMAccountName = $Surname + "" + $Initial
$SAMAccountLower = $SAMAccountName.ToLower()
$UserPrincipalName = $Surname+$Initial
$HD = "U"
$HDir = "\\RBHFILRED002\"
$AC = "Users_01$\"
$DH = "Users_02$\"
$IM = "Users_03$\"
$NS = "Users_04$\"
$TZ = "Users_05$\"
$Folder = if ($SInitial -in 'a','b','c'){$AC}
elseif ($SInitial -in 'd','e','f', 'g','h'){$DH}
elseif ($SInitial -in 'i','j','k', 'l','m'){$IM}
elseif ($SInitial -in 'n','o','p', 'q','r','s'){$NS}
else {$TZ}
$group1 = "zz Everyone"
$group2 = "Safeboot Domain Users"
$defaultname = $SAMAccountName
$email = $GivenName + "." + $Surname
$i = 1
cls
while ((Get-ADUser -Identity $SAMAccountName -ErrorAction SilentlyContinue) -ne $null) {
$SamAccountName = $defaultname + [string]$i
$Mail = $email + [string]$i + "#" + "royalberkshire.nhs.uk"
$i++
}
$NewUserParams = #{
Path = "OU=Users,OU=RBFT,DC=rbbh-tr,DC=nhs,DC=uk"
SamAccountName = $SAMAccountName
Name = $DisplayName
DisplayName = $DisplayName
GivenName = $GivenName
Surname = $Surname
EmailAddress = $Mail
UserPrincipalName = "$SAMAccountName#rbbh-tr.nhs.uk"
Title = $title
HomeDrive = $HomeDrive
HomeDirectory = "$HDir$Folder$SAMAccountName"
Description = $Description
ChangePasswordAtLogon = $true
PasswordNeverExpires = $false
AccountPassword = $defpassword
Enabled = $true
}
New-ADUser #NewUserParams
Add-ADGroupMember -Identity $group1 -Members $SAMAccountName
Start-Sleep -s 10
Add-ADGroupMember -Identity $group2 -Members $SAMAccountName
cls
echo "Please Wait Whilst We Find The AD Account & Create The Exchange Mailbox.."
Start-Sleep -s 30
Enable-Mailbox -Identity $SAMAccountName
cls
Any Ideas?
EDIT 1 - Error output:
Name : Microsoft.Exchange.Management.PowerShell.E2010
PSVersion : 1.0
Description : Admin Tasks for the Exchange Server
Name : Microsoft.Exchange.Management.Powershell.Support
PSVersion : 1.0
Description : Support Tasks for the Exchange Server
This tool is to be used for creating User Accounts for the RBFT Domain under
Ultima Business Solutions only. If this applies, please hit any key to continue.
Get-ADUser : Cannot find an object with identity: 'TimmsJ1' under: 'DC=rbbh-tr,DC=nhs,DC=uk'. At C:\Users\timmsj\Desktop\Scripts\User_Creation\RBFT_UC_Dev.ps1:140 char:9
+ While ((Get-ADUser -Identity $SAMAccountName -ErrorAction SilentlyCon ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (TimmsJ1:ADUser) [Get-ADUser], ADIdentityNotFoundException
+ FullyQualifiedErrorId : Cannot find an object with identity: 'TimmsJ1' u nder: 'DC=rbbh-tr,DC=nhs,DC=uk'.,Microsoft.ActiveDirectory.Management.Comm ands.GetADUser
New-ADUser : An attempt was made to add an object to the directory with a name that is already in use At C:\Users\timmsj\Desktop\Scripts\User_Creation\RBFT_UC_Dev.ps1:166 char:1
+ New-ADUser #NewUserParams
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=Timms James,...tr,DC=nhs,DC=uk:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : An attempt was made to add an object to the dire ctory with a name that is already in use,Microsoft.ActiveDirectory.Managem ent.Commands.NewADUser
Add-ADGroupMember : Cannot find an object with identity: 'TimmsJ1' under: 'DC=rbbh-tr,DC=nhs,DC=uk'.
At C:\Users\timmsj\Desktop\Scripts\User_Creation\RBFT_UC_Dev.ps1:167 char:1
+ Add-ADGroupMember -Identity $group1 -Members $SAMAccountName
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (TimmsJ1:ADPrincipal) [Add-ADGro upMember], ADIdentityNotFoundException
+ FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Micros oft.ActiveDirectory.Management.Commands.AddADGroupMember
Add-ADGroupMember : Cannot find an object with identity: 'TimmsJ1' under:
'DC=rbbh-tr,DC=nhs,DC=uk'. At C:\Users\timmsj\Desktop\Scripts\User_Creation\RBFT_UC_Dev.ps1:169 char:1
+ Add-ADGroupMember -Identity $group2 -Members $SAMAccountName
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (TimmsJ1:ADPrincipal) [Add-ADGroupMember], ADIdentityNotFoundException
+ FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember
Please Wait Whilst We Find The AD Account & Create The Exchange Mailbox..
Enable-Mailbox : The operation couldn't be performed because object 'TimmsJ1' couldn't be found on 'rbhdc8red002.rbbh-tr.nhs.uk'.
At C:\Users\timmsj\Desktop\Scripts\User_Creation\RBFT_UC_Dev.ps1:175 char:1
+ Enable-Mailbox -Identity $SAMAccountName
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (0:Int32) [Enable-Mailbox], Manage mentObjectNotFoundException
+ FullyQualifiedErrorId : 637D7B43,Microsoft.Exchange.Management.Recipient Tasks.EnableMailbox
Username:
TimmsJ1
Password:
Welcome123
Email:
James.Timms1#royalberkshire.nhs.uk
Job Title - Department:
Test - Ultima
Home Directory:
\\RBHFILRED002\Users_05$\TimmsJ1
You will need to manually set the new user's group memberships. Please Do This
Before Sending The User's Account Details.
Press Any Key To Close
The parameter -Name sets not only the attribute name but also cn (common name), which must be unique just like sAMAccountName. To fix the issue change this:
$NewUserParams = #{
Path = "OU=Users,OU=RBFT,DC=rbbh-tr,DC=nhs,DC=uk"
SamAccountName = $SAMAccountName
Name = $DisplayName
DisplayName = $DisplayName
...
}
into this:
$NewUserParams = #{
Path = "OU=Users,OU=RBFT,DC=rbbh-tr,DC=nhs,DC=uk"
Name = $SAMAccountName
DisplayName = $DisplayName
...
}
When omitting -SamAccountName the value of the parameter -Name is automatically assinged as the sAMAccountName too.
I want to create a new AD user but it is showing error message like:
New-ADUser : The object name has bad syntax
At C:\Users\sa\Desktop\AD User Script.ps1:22 char:1
+ New-ADUser -Name "$displayName" -UserPrincipalName "($initials) ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=fbfb regbgfn...IT,DC=,DC=it:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.NewADUser
$firstName = Read-Host "Indtast dit fornavn"
$middlename = Read-Host "Indtast dit mellemnavn (Hvis du ikke har et tryk Enter)"
$surname = Read-Host "Indtast dit efternavn"
$PlainPassword = "Admin100"
$SecurePassword = $PlainPassword | ConvertTo-SecureString -AsPlainText -Force
$group = Read-Host "Hvilken Gruppe? [1 - Help] [2 - Sof] [3 - In]"
$firstletter1 = $firstname.Substring(0, 1)
$secondletter = $firstname.Substring(0, 2)
$firstletter2 = $middlename.Substring(0, 1)
$firstletter3 = $surname.Substring(0, 1)
$displayName = "$firstName $middlename$surname"
if ($middlename -eq $Null) {
$initials = "$firstletter1$secondletter$firstletter3".ToLower()
Write-Host "$initials"
}
else {
$initials = "$firstletter1$firstletter2$firstletter3".ToLower()
Write-Host "$initials"
}
$Searcher = [ADSISearcher]"(sAMAccountName=$initials)"
$Results = $Searcher.FindOne()
If ($Results -eq $Null) {
If ($group -eq 1) {
New-ADUser -Name "$displayName" -UserPrincipalName "($initials)" -Path "OU=,OU=,OU-,OU=,DC=,DC=" -Enabled $true -AccountPassword $SecurePassword -ChangePasswordAtLogon $True -DisplayName "$initials" -GivenName "$firstname" -HomeDrive "P: \\fileshare\Privat\%$initials%" -Initials "$initials" -SamAccountName "$firstletter1" -Surname "$surname"
}
Can you check the UserPrincipalName and sAMAccountName formats. An example would be:
Name: John Smith
UPN: smithj#example.com
sAMAccountName : smithj
UPN Format
A UPN consists of a UPN prefix (the user account name) and a UPN suffix (a DNS domain name). The prefix is joined with the suffix using the "#" symbol. For example, "someone# example.com". A UPN must be unique among all security principal objects within a directory forest. This means the prefix of a UPN can be reused, just not with the same suffix.
I am working on a PowerShell command where I have a .csv file with a certain attributes, but am actually stuck in completing it.
The attributes of my .csv file are in the following order:
userPrincipalName
sAMAccountName
password
givenName
sn
displayName
description
Path
title
company
memberOf
department
mustChangePassword
My current code is this:
$Users = Import-Csv -Path "C:\BulkUsers.csv"
foreach ($User in $Users)
{
$UPN = $User.userPrincipalName
$SAM = $User.sAMAccountName
$Password = $User.password
$UserFirstname = $User.givenName
$UserLastname = $User.sn
$Displayname = $User.givenName + " " + $User.sn
$Description = $User.description
$Path = $User.Path
$Title = $User.title
$Company = $User.company
$Group = $User.memberOf
$Department = $User.department
New-ADUser -UserPrincipalName $UPN -SamAccountName $SAM -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -GivenName "$UserFirstname" -Surname "$UserLastname" -DisplayName "$Displayname" -Description "$Description" -Path "$Path" -title "$Title" -company "$Company" -memberOf "$Group" -department "$Department" -ChangePasswordAtLogon $true
}
Am getting the below error while executing it:
New-ADUser : A parameter cannot be found that matches parameter name 'memberOf'.
At line:15 char:292
+ ... any "$Company" -memberOf "$Group" -department "$Department" -ChangePasswordAtLo ...
+ ~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.NewADUser
The error message is pretty straightforward. If you take a look at the documentation for the New-ADUser cmdlet you'll see that it doesn't have a parameter -memberOf. To add the newly created user to a group use the Add-ADGroupMember cmdlet.
$Account = New-ADUser ... -PassThru
Add-ADGroupMember -Identity $Group -Members $Account
This is assuming that the memberOf field from the CSV contains just a single group name or distinguished name.
The additional parameter -PassThru allows you to assign the created account object to a variable, so you can use that variable in the group assignment. Without that parameter New-ADUser runs silently (without output).
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