Importing csv data into custom attribute in Active Directory - powershell

I have a .csv file that I am using to modify custom attributes on users in Active Directory, but PowerShell does not like the script:
Import-Csv -path c:\users\user\desktop\doc.csv | ForEach-Object {
Set-ADUser $_.mail -replace #{
ExtensionAttribute1 = $_.ExtensionAttribute1
}
}
I get the following error:
Set-ADUser : replace
At line:2 char:4
Set-ADUser $_.mail -replace #{
CategoryInfo: InvalidOperation: (user123:ADUser) [Set-ADUser], ADInvalidOperationException
FullyQualifiedErrorId: ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.SetADUser
The CSV only has 2 columns:
extensionAttribute1,mail
Any help would be appreciated

The -Identity parameter for Set-ADUser does not take an email address.
It needs either the DistinguishedName, objectGUID, SID or SamAccountName. You can also pipe a user object directly to the cmdlet.
Because of that, you need to first try to find the user with Get-ADUser and if that succeeds set the attribute.
Import-Csv -Path 'c:\users\user\desktop\doc.csv' | ForEach-Object {
$user = Get-ADUser -Filter "EmailAddress -eq '$($_.mail)'" -ErrorAction SilentlyContinue
if ($user) {
$user | Set-ADUser -Replace #{ extensionAttribute1 = $_.extensionAttribute1 }
}
else {
Write-Warning "No user with email address '$($_.mail)' found.."
}
}
PS. I always use the exact LDAP name inside the Hash for the key name when using -Add, -Replace etc. Case sensitive.

Related

Import Data issue from CSV to AD

I have a problem importing phone numbers from a CSV file based on email addresses to Active directory using a PowerShell script.
The table contains:
mail;telephoneNumber
toto#domaine.com;88888888
tata#domaine.com;99999999
here’s the code I’m running but it shows me an error message, or I don’t see why there’s this message:
Import-module ActiveDirectory
Import-CSV E: scripts list.csv |
ForEach-Object {
Write-Host "telephoneNumber $($_.telephoneNumber)"
Get-ADUser -Filter "mail -like '$($_.mail)'" |
Set-ADUser -telephoneNumber $_. telephoneNumber}
Here is the error message:
telephoneNumber
Set-ADUser: Unable to find a parameter corresponding to the name «telephoneNumber».
Character E: scripts employeeid.ps1:6: 14
+ Set-ADUser -telephoneNumber $_. telephoneNumber}
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-ADUser], ParameterBindingException
+ FullyQualifiedErrorId: NamedParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.SetADUser
NB: I am a beginner in the subject
Thank you well in advance for your help
I tried this code too but still the same problem.
Import-module ActiveDirectory
Import-CSV "E:\scripts\liste.csv" | % {
$telephoneNumber = $_.telephoneNumber
$mail= $ail_.m
Set-ADUser $telephoneNumber -mail $mail
}
The LDAP property telephoneNumber is known as OfficePhone in PowerShell and LDAP property mail has a PowerShell equivalent called EmailAddress.
Cmdlet Set-ADUser does not have a parameter called telephoneNumber, but it does have OfficePhone, so a rewrite of your code would be
Import-Module ActiveDirectory
Import-Csv -Path 'E:\scripts\list.csv' | ForEach-Object {
$user = Get-ADUser -Filter "mail -eq '$($_.mail)'" # or use PS equivalent 'EmailAddress'
if ($user) {
Write-Host "Setting telephoneNumber $($_.telephoneNumber) for $($user.Name)"
$user | Set-ADUser -OfficePhone $_.telephoneNumber
# if you do want to use LDAP property telephoneNumber, you can use below
# $user | Set-ADUser -replace #{telephoneNumber = $($_.telephoneNumber)}
}
else {
Write-Warning "Could not find user with EmailAddress $($_.mail)"
}
}
P.S. you made some typos when posting:
E: scripts list.csv is missing the backslashes
$_. telephoneNumber has a space between the dot and the property name

PowerShell Add AD users to AD group by UPN from CSV

Import-CSV "C:\Temp\jacktest.csv" | Foreach-Object {
$aduser = Get-ADUser -Filter "UPN-eq '$($_.UPN)'"
if( $aduser ) {
Write-Output "Adding user $($aduser.SamAccountName) to groupname"
Add-ADGroupMember -Identity JackTest -Members $aduser
} else {
Write-Warning "Could not find user in AD with email address $($_.EmailAddress)"
}
}
I receive the following Error:
Transcript started, output file is C:\Temp\Add-ADUsers.log
Get-ADUser : The search filter cannot be recognized
At line:19 char:15
$ADUser = Get-ADUser -Filter "UPN -eq '$UPN'" | Select-Object Sam ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : NotSpecified: (:) [Get-ADUser], ADException
FullyQualifiedErrorId : ActiveDirectoryServer:8254,Microsoft.ActiveDirectory.Management.Commands.GetADUser
This answer is meant to help you troubleshoot your issue so we can understand what could be going wrong with your CSV.
Note, this code assumes that your CSV is comma delimited and the CSV has a column with name "UserPrincipalName".
$usersToAdd = foreach($line in Import-CSV "C:\Temp\jacktest.csv")
{
if([string]::IsNullOrWhiteSpace($line.UserPrincipalName))
{
Write-Warning 'Empty UserPrincialName Value:'
Write-Warning $line
continue
}
$aduser = Get-ADUser -Filter "UserPrincipalName -eq '$($line.UserPrincipalName)'"
if(-not $aduser)
{
Write-Warning "$($line.UserPrincipalName) could not be found."
continue
}
$aduser
}
if($usersToAdd)
{
Write-Host 'The following users will be added to the Group'
$usersToAdd.UserPrincialName
try
{
Add-ADGroupMember -Identity JackTest -Members $usersToAdd
}
catch
{
Write-Warning $_.Exception.Message
}
}
check the csv file, it seems you are not using the default delimiter.
if so add parameter -delimiter to the import-csv cmdlet.
for example for Tab delimiter:
Import-CSV "C:\Temp\jacktest.csv" -delimiter "`t"

Updating Active Directory Manager Attribute from .csv Using PowerShell

I'm not so good at PowerShell. I have this script which worked before that I've have used to update the manager attribute in Active Directory, however, now after just replacing the file its no longer working
$Users = Import-CSV C:\Documents\Managers.csv
ForEach ($User in $Users) {
$user= Get-ADUser -Filter "displayname -eq '$($Users.EmployeeFullName)'"|select -ExpandProperty samaccountname
$manager=Get-ADUser -Filter "displayname -eq '$($Users.'Line Manager Fullname')'"|select -ExpandProperty DistinguishedName
Set-ADUser -Identity $user -Replace #{manager=$manager}
}
when running the script it returns:
Set-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the argument, and then try running the command again.
At line:6 char:22
+ Set-ADUser -Identity $user -Replace #{manager=$manager}
+ ~~~~~
+ CategoryInfo : InvalidData: (:) [Set-ADUser], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.SetADUser
the "EmployeeFullName" and "Line Manager FullName" format in the .csv is set as i.e. joe bloggs, see below CSV file example.
EmployeeFullname Line Manager Fullname
---------------- ---------------------
Kieran Rhodes Tracey Barley
Lewis Pontin Tracey Barley
Lizzy Wilks Rodney Bennett
I also noticed if I remove and try to retype "$Users.EmployeeFullName" it no longer picks up the "EmployeeFullName" from the csv file.
Anyone know what I'm doing wrong here please?
Below would be an example:
$Users = Import-CSV C:\Documents\Managers.csv
ForEach ($User in $Users) {
$user = Get-ADUser -Filter "displayname -eq '$($User.EmployeeFullName)'"
$manager = (Get-ADUser -Filter "displayname -eq '$($User.'Line Manager Fullname')'").DistinguishedName
Set-ADUser -Identity $User -Replace #{manager=$manager}
}
Note: you don't need to dig down to the samAccountName property because Set-ADUser will take the full fidelity object for the -Identity argument. You also don't need to use Select... -ExpandProperty you can just parenthetically dot reference the distinguishedName property.
Also you can use the instancing capability in the AD cmdlets:
$Users = Import-CSV C:\Documents\Managers.csv
ForEach ( $User in $Users )
{
$User = Get-ADUser -Filter "displayname -eq '$($User.EmployeeFullName)'" -Properties Manager
$Manager = (Get-ADUser -Filter "displayname -eq '$($User.'Line Manager Fullname')'").DistinguishedName
$User.Manager = $Manager
Set-ADUser -Instance $User
}
In this case you call back the Manager property set it with a simple assignment statement than give the $User variable as the argument to the -Instance parameter of Set-ADUser

Power Shell CSV to AD

Maybe someone can to help?
I have a script it take parameters from scv and put them to AD, script work without mistakes but I`m does not have results from some reasone.
Please help!
Import-CSV -Path "$home\desktop\Scripts\test4.scv" | ForEach-Object -process {Write-Host $_ }
{Set-ADuser|]= -Identity $_.DisplayName -extensionattribute5 $_.extensionattribute5}
example scv
According to the docs, the -Identity parameter on Set-ADUser must be one of
A distinguished name
A GUID (objectGUID)
A security identifier (objectSid)
A SAM account name (sAMAccountName)
This means that you cannot use the DisplayName property from the CSV for this parameter.
Try:
Import-CSV -Path "$home\desktop\Scripts\test4.scv" | ForEach-Object {
$user = Get-ADUser -Filter "DisplayName -eq '$($_.DisplayName)'" -Properties DisplayName -ErrorAction SilentlyContinue
if ($user) {
Write-Host "Setting extensionattribute5 property for user $($_.DisplayName)"
$user | Set-ADuser -Add #{extensionattribute5=$_.extensionattribute5}
}
else {
Write-Warning "User $($_.DisplayName) could not be found"
}
}
Instead of -Add #{extensionattribute5=$_.extensionattribute5}, you may rather want -Replace #{extensionattribute5=$_.extensionattribute5}. This isn't clear in the question
Try this:
Import-CSV -Path "$home\desktop\Scripts\test4.scv" | ForEach {
Write-Host $_
Set-ADuser -Identity $_.DisplayName -Add #{extensionattribute5=$_.extensionattribute5}
}
Your code was broken. Bracing was incorrect. Also Extended attributes are added with a hash table using -Add parameter.

Change Active Directory titles for all csv users

I would like to change 150 employees their job title.
I have a csvfile called Titletest.csv with columns UserPrincipalName [the user.name under it] and Title [job title under it]
The PowerShell script:
Import-Module ActiveDirectory
$users = Import-Csv -Path c:\scripts\Titlestest.csv | Foreach-Object {
$user = $_.user
$title = $_.title
#Selects the specified user and sets Job Title
Get-ADUser -Filter {(UserPrincipalName -eq $user)} | Set-ADUser -Title $title
}
I get errors saying:
Get-ADUser : Variable: 'user' found in expression: $user is not defined.
At line:14 char:1
+ Get-ADUser -Filter {(UserPrincipalName -eq $user)} | Set-ADUser -Titl ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADUser], ArgumentException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADUser
Can someone please advise?
Thank you.
The reason for your error is because $user has no assignment. You are attempting to assign $user the value of a property that does not exist. The header user apparently does not exist in your CSV file. See below for how to convert a csv into PowerShell objects and access their properties.
# Sample CSV TitleTest.csv
UserPrincipalName,Title
covid19#domain.com,Usurper
jsmith#domain.com,CEO
bossman#domain.com,CFO
Import-Csv -Path c:\scripts\TitleTest.csv | Foreach-Object {
$user = $_.UserPrincipalName
$title = $_.Title
Get-ADUser -Filter 'UserPrincipalName -eq $user' | Set-ADUser -Title $title
}
Explanation:
When using Import-Csv on a proper CSV file, the first row of delimited data will be converted to the properties of all input objects. All succeeding rows will be converted to individual objects with the header properties and output as a collection (array) of those objects. If the -Header parameter is used, then values passed into the parameter will become the properties of the objects. It is important to have the same number of delimited items on each row to ensure proper mapping.
Once you are dealing with objects, you can access their property values using the member access operator .. The syntax is object.property. So since you have headers UserPrincipalName and Title, you will need to use $_.UserPrincipalName and $_.Title to access the associated values.
$_ is the current pipeline object within your Foreach-Object {} script block.
Note that you don't technically need to define $user and $title here. You can just access the properties directly from the current object:
Import-Csv -Path c:\scripts\TitleTest.csv | Foreach-Object {
Get-ADUser -Filter "UserPrincipalName -eq '$($_.UserPrincipalName)'" |
Set-ADUser -Title $_.Title
}