Updating AD User Object Manager Attribute With Contact DN - powershell

I have two forests after a merger. Managers of some people reside in the opposite forest. To get around this we have contacts in each forest for all the users of the opposite forest. I am trying to update the manager attribute for several users based on a csv import where I am matching on the managers email address. My script can match the DN of the managers contact, but for some reason will not add it to the ad userobject manager attribute stating it cannot find the DN of an object that is clearly present.
If I run a simple get-adobject with an ldap filter it returns the DN of a managers contact:
PS C:\temp> Get-ADObject -ldapfilter "(&(objectclass=contact)(name=$fname*)(name=*$lname))" -SearchBase "OU=station,OU=CONTACTS,DC=workplace,DC=COM" |select distinguishedname
distinguishedname
-----------------
CN=Nick Hill,OU=station,OU=Contacts,DC=workplace,DC=com
However, the script below will error when trying to add this DN to a users manager attribute. What's confusing is the DN it claims it cannot find is clearly present per the command above.
The script below errors with:
set-aduser : Identity info provided in the extended attribute: 'Manager' could not be resolved. Reason: 'Cannot find an object with identity: 'CN=Nick Hill,OU=station,OU=Contacts,DC=workplace,DC=com' under: 'DC=workplace,DC=com'.'.
$users = import-csv test1.csv
FOREACH ($user in $users)
{
$username = $user.UserName
$employeeid = $user.employeeid
$city = $user.city
$country = $user.country
$department = $user.department
$division = $user.division
$office = $user.location
$state = $user.state
$postalcode = $user.postal_code
$manageremail = $user.manageremail
$manager = get-aduser -f "mail -eq '$($manageremail)'"
FUNCTION LocalManager
{
get-aduser -f {mail -eq $username} |set-aduser -Manager $manager
}
FUNCTION RemoteManager
{
$data = $manageremail.split("#")
$name = $data[0]
$namesplit = $name.split(".")
$fname = $namesplit[0]
$lname = $namesplit[1]
$rmanager = Get-ADObject -SearchBase 'OU=station,OU=Contacts,DC=workplace,DC=com' -ldapfilter "(&(objectclass=contact)(name=$fname*)(name=*$lname))"
get-aduser -f {mail -eq $username} |set-aduser -Manager "$rmanager"
}
IF ($manager -eq $null)
{
RemoteManager
}
Else
{
Localmanager
}
}

I have had a similar error on my own script to handle cross-domain user population. I've exported some of our old decom'd user accounts and am importing them (with suitably generic information) to populate our test/dev environments.
Unfortunately when I try and create these accounts as new users in AD with managers in different domains, I find the following problem:
Set-ADUser : The server is unwilling to process the request
At line:1 char:1
+ Set-ADUser -Identity $user.SamAccountName -Manager $user.Manager -Ser ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (user.name:ADUser) [Set-ADUser], > ADInvalidOperationException
+ FullyQualifiedErrorId : > ActiveDirectoryServer:8245,Microsoft.ActiveDirectory.Management.Commands.SetADUser
So this was in an attempt to set the user with the manager's DN.
function create-testaccts {
[CmdletBinding()]
param(
[Parameter(Mandatory=$True,Position=1)]
[string] $rootPath ,
[Parameter(Mandatory=$True,Position=2)]
[string] $userList ,
[Parameter(Mandatory=$True,Position=3)]
[string] $pw ,
[Parameter(Mandatory=$True,Position=4)]
[string] $OU = $(throw "Please specify a query.")
)
$newUsers = import-csv $userList
$password = $pw | ConvertTo-SecureString -AsPlainText -Force
foreach ($user in $newUsers){
$profPath = $rootpath + $user.samaccountname
try {
write-host -fore Cyan "Creating the user profile path - $profPath"
new-item $profPath -ItemType Directory -Force -ErrorAction stop | Out-Null
}# END OF TRY
Catch [System.Management.Automation.ActionPreferenceStopException] {
write-host -fore Yellow "caught a StopExecution Exception - Home directory creation "
$error[0]
}# END OF CATCH
try {
Write-Host -Fore Cyan "Creating the user object in AD -" $user.Name
# Name - Name
# Givenname - Firstname
# Surname - Lastname
# Password - AccountPassword Specific to new-aduser
# SamAccountName - same in both command/attribute name used userlogon and samaccount
# Manager - same in both command/attribute name
# ProfilePath - same in both command/attribute name
# HomeDirectory - same in both command/attribute name
# HomeDrive - same in both command/attribute name
# Enabled - False - same in both command/attribute name
# UserPrincipalName - same in both command/attribute name
# Server
$name = $user.Name
New-ADUser -Name "$name" `
-GivenName $user.givenname `
-Surname $user.surname `
-DisplayName $user.displayname `
-SamAccountName $user.SamAccountName `
-Path $ou `
-AccountPassword $Password `
-ProfilePath $user.profilepath `
-HomeDirectory $user.HomeDirectory `
-HomeDrive $user.homedrive `
-Enabled $False `
-UserPrincipalName $user.UserPrincipalName `
-Server domain.local `
-Credential $creds `
-ErrorAction Stop
#-Manager $user.Manager `
}# END OF TRY
Catch [System.Management.Automation.ActionPreferenceStopException] {
Write-Host -fore Yellow "caught a StopExecution Exception - Account Creation"
$error[0]
}# END OF CATCH
}#END FOREACH NEW USERS
} #END OF FUNCTION (CREATE-TESTACCTS)
When I try and use this with a trusted domain it fails due to the manager DN not being found in the local domain. I've tried multiple ways, but can't seem to find out why it does this and won't seem to chain.
However i found a workaround where i can create the user without the mgr field and then set the user using the following link/command:
https://social.technet.microsoft.com/Forums/office/en-US/ade19ad5-ecfd-48af-987b-5958983676b6/active-directory-update-the-manager-field-when-the-manager-is-in-a-different-domain?forum=ITCG
Set-ADUser -Identity $ADUser_Domain1 -Credential $DomainAdmin_Domain1 -Server $Domain1 -Replace #{manager = $ManagerDN_Domain2}
This works and I have no idea why the replace works, but seems to require the credential being passed. I've even tried with passing the domain 2 credential.
Overall this is very confusing and i feel like if the local session credential has rights between domains it should be able to look this up without issue. Any additional help or explanation would be REALLY helpful!

Related

If AD account exists, append a counter to the username started at 2

The following script is adding accounts to the Active Directory. In case the username already exists, I want to append a number to the username and try again.
i.e. if cs15csa already exists, it should try again with cs1csa2. If cs1csa2 exists, it should then try with cs1csa3 and so on and so forth.
How do I do that?
# Enter a path to your import CSV file
$ADUsers = Import-csv export.csv
foreach ($User in $ADUsers)
{
$Username = $User.username
$Password = $User.password
$Firstname = $User.firstname
$Lastname = $User.lastname
$OU = $User.ou
# Check if the user account already exists in AD
if (Get-ADUser -F {SamAccountName -eq $Username})
{
# If user does exist, output a warning message
Write-Warning "A user account $Username ($Firstname $Lastname) already exists in the Active Directory."
}
else
{
# If a user does not exist then create a new user account
# Account will be created in the OU listed in the $OU variable in the CSV file; don't forget to change the domain name in the"-UserPrincipalName" variable
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Username#iit.uni-ruse.bg" `
-Email "$Username#iit.uni-ruse.bg" `
-ProfilePath '\\leo\%USERNAME%\Profile' `
-Name "$Username" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-DisplayName "$Firstname $Lastname" `
-Path $OU `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force)
}
}
You can simply use a loop to test the SamAccountName and inside keep adding a counter number to it until you have found a unique name.
To avoid having to use those nasty backticks on the New-ADUser cmdlet, I would advise to use Splatting
Also, '\\leo\%USERNAME%\Profile' should be "\\leo\$Username\Profile"
Try
# Enter a path to your import CSV file
$ADUsers = Import-Csv export.csv
foreach ($User in $ADUsers) {
$Username = $User.username
# Check if the user account already exists in AD and keep adding
# a counter value to the SamAccountName until unique
$count = 2
while (Get-ADUser -Filter "SamAccountName -eq '$Username'") {
$Username = '{0}{1}' -f $User.username, $count++
}
# create the new user using a Splatting Hashtable
$userParams = #{
SamAccountName = $Username
UserPrincipalName = "$Username#iit.uni-ruse.bg"
EmailAddress = "$Username#iit.uni-ruse.bg"
ProfilePath = "\\leo\$Username\Profile"
Name = $Username
GivenName = $User.firstname
Surname = $User.lastname
Enabled = $true
DisplayName = '{0} {1}' -f $User.firstname, $User.lastname
Path = $User.ou
AccountPassword = $User.password | ConvertTo-SecureString -AsPlainText -Force
}
# create the user
New-ADUser #userParams
}
An alternative to the while loop above (might be faster, depending on how many similar SamAccountNames there may be in your environment) would be to do this:
# Check if the user account already exists in AD and keep adding
# a counter value to the SamAccountName until unique
# first get an array of similar SamAccountNames already present
$similarNames = #((Get-ADUser -Filter "SamAccountName -like '$Username*'").SamAccountName)
$count = 2
while ($similarNames -contains $Username) {
$Username = '{0}{1}' -f $User.username, $count++
}

Powershell issue when creating new user then give them group and move to specific OU

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")

Directory Object Not Found - Active Directory - Inputting from CSV

hi there im trying to import user accounts from a CSV file to Active Directory but i've been trying for hours to no avail. Basically I have the CSV file i want to import. So I've been trying multiple powershell scripts and getting the same error
CSV contents:
GivenName,Surname,Name,SamAccountName,Path,userPrincipalName
Scooby,Doo,Scooby,Scooby,"OU=Vehicles,OU=Production,DC=csc,DC=local",scooby#csc.local
Shaggy,Rogers,Shaggy,Shaggy,"OU=Vehicles,OU=Production,DC=csc,DC=local",shaggy#csc.local
Fred,Jones,Fred,Fred,"OU=Weapons,OU=Production,DC=csc,DC=local",fred#csc.local
Daphne,Blake,Daphne,Daphne,"OU=Weapons,OU=Production,DC=csc,DC=local",daphne#csc.local
Velma,Dinkley,Velma,Velma,"OU=Weapons,OU=Production,DC=csc,DC=local",velma#csc.local
Pat,Pending,Pat,Pat,"OU=Biological,OU=Research,DC=csc,DC=local",pat#csc.local
Red,Max,Red,Red,"OU=Biological,OU=Research,DC=csc,DC=local",red#csc.local
Peneolope,Pitstop,Peneolope,Peneolope,"OU=Biological,OU=Research,DC=csc,DC=local",peneolope#csc.local
Peter,Perfect,Peter,Peter,"OU=Energy,OU=Research,DC=csc,DC=local",peter#csc.local
Rock,Slag,Rock,Rock,"OU=Energy,OU=Research,DC=csc,DC=local",rock#csc.local
Gravel,Slag,Gravel,Gravel,"OU=Energy,OU=Research,DC=csc,DC=local",gravel#csc.local
Luke,Bear,Luke,Luke,"OU=Energy,OU=Research,DC=csc,DC=local",luke#csc.local
Rufus,Ruffcut,Rufus,Rufus,"OU=Energy,OU=Research,DC=csc,DC=local",rufus#csc.local
Dick,Dastardly,Dick,Dick,"OU=Energy,OU=Research,DC=csc,DC=local",dick#csc.local
Rick,Sanchez,Rick,Rick,"OU=Board,OU=Management,DC=csc,DC=local",rick#csc.local
Morty,Smith,Morty,Morty,"OU=Board,OU=Management,DC=csc,DC=local",morty#csc.local
Beth,Smith,Beth,Beth,"OU=HR,OU=Management,DC=csc,DC=local",beth#csc.local
Powershell Script:
#Enter a path to your import CSV file
$ADUsers = Import-csv C:\scripts\csc.csv
foreach ($User in $ADUsers)
{
$Username = $User.SamAccountName
$Password = $User.Password
$Firstname = $User.Name
$Lastname = $User.Surname
$OU = $User.Path
#Check if the user account already exists in AD
if (Get-ADUser -F {SamAccountName -eq $Username})
{
#If user does exist, output a warning message
Write-Warning "A user account $Username has already exist in Active Directory."
}
else
{
#If a user does not exist then create a new user account
#Account will be created in the OU listed in the $OU variable in the CSV file; don’t forget to change the domain name in the"-UserPrincipalName" variable
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Username#csc.local" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-ChangePasswordAtLogon $True `
-DisplayName "$Lastname, $Firstname" `
-Path $OU `
-AccountPassword $Password `
}
}
Output from powershell:
New-ADUser : Directory object not found
At C:\scripts\Add-NewUsers.ps1:24 char:25
+ New-ADUser <<<< `
+ CategoryInfo : ObjectNotFound: (CN=Rick Sanchez...DC=csc,DC=local:String) [New-ADUser], ADIdentityN
undException
+ FullyQualifiedErrorId : Directory object not found,Microsoft.ActiveDirectory.Management.Commands.NewADUser
this error is repeated 7 times or so but the only thing different is the name (where is says ObjectNotFound(CN=Rick Sanchez..) different name for each error
Try adding this try catch block to your code, according to some googling this error is related to the OU where you want to create the new users not existing.
$ErrorActionPreference = 'Stop'
foreach ($User in $ADUsers)
{
$Username = $User.SamAccountName
$Password = $User.Password
$Firstname = $User.Name
$Lastname = $User.Surname
$OU = $User.Path
try
{
Get-ADOrganizationalUnit $OU
}
catch
{
"Creating OU: $OU"
$name, $path = $OU.Split(',',2)
New-ADOrganizationalUnit -Name $name.Replace('OU=','') -Path $path
}
# Continue script here
}
Unrelated but, you might also want to consider start using splatting on your code for obvious reasons:
$params = #{
SamAccountName = $Username
UserPrincipalName = "$Username#csc.local"
Name = "$Firstname $Lastname"
GivenName = $Firstname
Surname = $Lastname
Enabled = $True
ChangePasswordAtLogon = $True
DisplayName = "$Lastname, $Firstname"
Path = $OU
AccountPassword = $Password
}
New-ADUser #params

Powershell Active Directory username

For a school project, i need to make a Powershell script, but to create a username, with only the first letter of the person name, and the full second name, could anyone help me with this? This is what i currently have:
Import-Module ActiveDirectory
# password for accounts
$securePassword = ConvertTo-SecureString "Welkom#1" -AsPlainText -Force
# Import the file into a variable
$users = Import-Csv -Path .\New-GaastraUserBulk.csv
# Loop trough each row, and gather Information
ForEach ($user in $users) {
# Gather the user Information
$fname = $user.FirstName
$lname = $user.LastName
$jtitle = $user.JobTitle
$OUpath = $user.OU
Write-Host $fname
Write-Host $lname
Write-Host $jtitle
Write-Host $OUpath
#Gebruiker aanmaken in AD
New-ADUser -Name "$fname $lname" -GivenName $fname -SamAccountName $lname -Surname $lname -UserPrincipalName "$lname" -Path $OUpath -AccountPassword $securePassword -PasswordNeverExpires $true -Enabled $true
}
As per the comments from others. Add this line after $lname = ...
$sam = "{0}$lname" -f $fname.Substring(0,1)
Then edit your New-ADUser line use $sam
New-ADUser .... -SamAccountName $sam ...
Turning my comment into an answer.
You can create the user's SamAccountName quite easily, combining the first character of the users GivenName with the full LastName. However, you need to check that this SamAccountName is not already in use.
Another thing is that the UserPrincipalName should be in the form of <user>#<DNS-domain-name>.
To improve your code also using Splatting:
Import-Module ActiveDirectory
# password for accounts
$securePassword = ConvertTo-SecureString "Welkom#1" -AsPlainText -Force
# Import the file into a variable
$users = Import-Csv -Path .\New-GaastraUserBulk.csv
# Loop trough each row, and gather Information
foreach ($user in $users) {
# first create the desired SamAccountName for the new user
$accountName = "{0}{1}" -f $user.FirstName.Substring(0,1),$user.LastName
# test if a user with that SamAccountName already exists
$checkUser = Get-ADUser -Filter "SamAccountName -eq '$accountName'" -ErrorAction SilentlyContinue
if ($checkUser) {
Write-Warning "SamAccountName $accountName already used for user $($checkUser.Name)"
}
else {
# create a hashtable with all parameters for the New-ADUser cmdlet
$userParams = #{
Name = "$fname $lname"
GivenName = $user.FirstName
Surname = $user.LastName
Title = $user.JobTitle
SamAccountName = $accountName
Path = $user.OU
AccountPassword = $securePassword
PasswordNeverExpires = $true
Enabled = $true
UserPrincipalName = "$accountName#yourdomain.com" # <-- put YOUR domain here after the '#'
# other parameters go here if needed
}
New-ADUser #userParams
}
}
Also, keep in mind that you cannot use just any character for a SamAccountName.
Characters " [ ] : ; | = + * ? < > / \ , # are illegal, aswell as non-printable characters and the dot . can not be the last character of the name.
AND, the system limits sAMAccountName to 20 characters for user objects.
To make sure, use something like:
$accountName = ($accountName -replace '["\[\]:; |=+\*\?<>/\\,#]').TrimEnd(".") -replace '^(.{1,20}).*', '$1'

Powershell issue with a defined variable

I am pretty new to powershell and have a code that I found. I had it working but now it is no longer working. I didn't change anything with the variable so I am not sure what is going on. Here is a link to a Screenshot of the code and error. Please let me know if you need any other information
https://imgur.com/a/ntEhdoV
Thank you!
Import-Module activedirectory
$ADUsers = Import-csv 'C:\Users\Desktop\Powershell files\EM-mis-new-AD.csv'
foreach ($User in $ADUsers)
{
$Username = $User.username
$Password = $User.password
$Firstname = $User.firstname
$Lastname = $User.lastname
$OU = $User.ou
$Password = $User.Password
if (Get-ADUser -F {SamAccountName -eq $Username})
{
Write-Warning "A user account with username $Username already exist in Active Directory."
}
else
{
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName "$Username#Mydomain" `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-DisplayName "$Firstname, $Lastname" `
-Path $OU `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $True
}
}
Error:
Get-ADUser : Variable: 'Username' found in expression: $Username is not defined.
At C:\Users\jcarnovale\Desktop\Testing if.ps1:22 char:6
if (Get-ADUser -F {SamAccountName -eq $Username})
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidArgument: (:) [Get-ADUser], ArgumentException
FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADUse
You probably want to check that you have a good username before proceeding in the script, like:
$Username = $User.username
...
if(!$Username) {
throw "Username was empty!"
}
Also, try changing the Get-ADUser filter to use a string:
if (Get-ADUser -F "SamAccountName -eq $Username")
{
}
You didn't show us anything of the imported CSV file itself and I think the main problem is in there.
Import-Csv by default expects the comma (,) to be used as delimiter character. If that is not the case in your file, you need to add parameter -Delimiter followed by the character that is used as separator in your file (like -Delimiter ';' if your file uses the semicolon).
Please check that first, so the Import-Csv cmdlet can parse the file correctly.
Next, it could be that there are empty values in the username column and if so, the code should skip these rows.
Also, as commented, the -Filter parameter needs a double-quoted string "Property -eq 'something'" in which a variable like $username is expanded, instead of a scriptblock {..}
Finally, I'd recommend using Splatting on cmdlets that take many properties instead of using backticks.
Try
Import-Module ActiveDirectory
# this defaults to csv fields delimited by a comma. If your CSV file uses a different
# character, then add parameter '-Delimiter' followed by the actual character
$ADUsers = Import-Csv -Path 'C:\Users\Desktop\Powershell files\EM-mis-new-AD.csv'
# the Where-Object clause is just a precaution to omit records that have no username value
$ADUsers | Where-Object { $_.username -match '\S'} | ForEach-Object {
$Username = $_.username
if (Get-ADUser -Filter "SamAccountName -eq '$Username'" -ErrorAction SilentlyContinue) {
Write-Warning "A user account with SamAccountName '$Username' already exist in Active Directory."
}
else {
$Firstname = $_.firstname
$Lastname = $_.lastname
# use splatting on cmdlets that use a lot of parameters
$userParams = #{
SamAccountName = $Username
UserPrincipalName = "$Username#Mydomain.com"
Name = "$Firstname $Lastname"
GivenName = $Firstname
Surname = $Lastname
Enabled = $true
DisplayName = "$Firstname, $Lastname"
Path = $_.ou
AccountPassword = (ConvertTo-SecureString $_.Password -AsPlainText -Force)
ChangePasswordAtLogon = $true
}
# create the user and report back
New-ADUser #userParams
Write-Host "Created new user '$Username' with initial password: $($_.Password)"
}
}