Update Active Directory "mail" attribute via PowerShell - powershell

I'm trying to update the email address listed in AD for all the users in a particular OU. This is the powershell script I'm using, but it's not working properly
Import-Module ActiveDirectory
Get-ADUser -Filter * -SearchBase "OU=OtherOU,OU=SomeOu,DC=Domain,DC=local" | Set-ADUser -email $_.samaccountname#domain.com
I think it's because $_.samaccountname isn't returning anything when I try to do Set-ADUser.
Can anyone point me in the right direction for fixing this? Thanks!

Create a csv file with SamAccountName & email address
"SamAccountName","EmailAddress"
"john","john#xyz.com"
step 1: import to a variable
$users = Import-Csv .\email.csv
step 2: Call the variable
foreach ($user in $users) {
Set-ADUser -Identity $user.SamAccountName -EmailAddress $user.EmailAddress
}

In the current context $_ is null. You need to use Foreach-Object in order for $_ to be available.
Get-ADUser -Filter * ... | Foreach-Object{
Set-ADUser -Identity $_ -Email "$($_.samaccountname)#domain.com"
}

I suspect you'll need to use a subexpression for that:
"$($_.samaccountname)#domain.com"

Assuming username is domain\user1 or user1#domain.com
$user = "user1"
Set-ADUser $user -emailaddress "firtname.lastname#xyz.com"
Get-ADUser -Identity $user -Properties emailaddress

Get-ADUser -Filter * -SearchScope Subtree -SearchBase "OU=OUName,DC=domain,DC=com" |
Foreach-Object { Set-ADUser -Identity $_ -Email "$($_.samaccountname)#domain.com" }
This is from:
https://social.technet.microsoft.com/wiki/contents/articles/33311.powershell-update-mail-and-mailnickname-for-all-users-in-ou.aspx

Related

Set-ADuser in Foreach

I tried to set the value Company into the ad field Company and it should Filter by Homepage (this works). And I get this error:
cmdlet Set-ADUser at command pipeline position 1
Supply values for the following parameters:
Identity:
$users = $null
$users = Get-ADUser -Filter 'Homepage -like "www.test.ch"' -Searchbase “OU=TestOu, OU=test Lyss, DC=ads,DC=test,DC=CH"
ForEach($user in $users)
{
Set-ADUser -Identity -Company 'Company'
}
Right, in your foreach loop, you're calling the -Identity parameter but never giving any value to the argument, like -Identity $user. In addition, it can be piped directly:
Get-ADUser -Filter "Homepage -like 'www.test.ch'" -Searchbase 'OU=TestOu,OU=test Lyss,DC=ads,DC=test,DC=CH' |
Set-ADUser -Company 'Company'

Renaming AD user object name in powershell

I am trying to get only AD Objects of type user and then iterate over all them and change AD user object name. So I have done below:
$Users = Get-ADObject -Filter {(ObjectClass -eq "user")} # OR Get-ADObject -Filter 'ObjectClass -eq "user"'
$Users | foreach
{
# Here code to create name based on conditions ($newUserObjectName)
Rename-ADObject -Identity $_ -NewName $newUserObjectName
}
The problem is that Get-ADObject is returning not only users but also computer objects.... I only want user object classes. Also I am not sure If below line of code is correct by setting identity to $_ in order to update the current user in the iteration:
Rename-ADObject -Identity $_ -NewName $newUserObjectName
Why not use Get-ADUser instead of Get-ADObject and just return the DistinguishedName? Obviously, DON'T just run this code :)
$users = (Get-ADUser -Filter *).DistinguishedName #This gets all the users in AD
Foreach($user in $users){
Rename-ADObject -Identity $user -NewName $newUserObjectName
}
The Computer objectClass is derived from the User objectClass. Hence, queries for user class will return both Computers and Users. If you want to filter for Users only, you have to specify ObjectCategory as Person
$Users = Get-ADObject -Filter {(Objectclass -eq "user") -and (objectCategory -eq "Person")}
Use that or you can use the goodole Get-ADuser
Use Get-ADUser and Set-ADUser:
$Users = Get-ADUser -Filter *
$Users | foreach {
# Naming code
Set-ADUser -Identity $_.SamAccountName -SamAccountName $newName
}
This replaces all user's identities to $newName.
Note you can replace -SamAccountName with any other property of an ADUser. for example if you want to replace the display name instead, you would use -Name $newName

Powershell-Update attribute "departmentNumber"

I have the following script - it works except for the departmentNumber. Any ideas?
# Import AD Module
Import-Module ActiveDirectory
# Import CSV into variable $users
$users = Import-Csv -Path C:\users.csv
# Loop through CSV file and update users if they exist
foreach ($user in $users) {
Get-ADUser -Filter "SamAccountName -eq '$($user.samaccountname)'" - Properties * |
Set-ADUser -EmailAddress $($user.EmailAddress) -Title $($user.Title) -Office $($user.Office) -OfficePhone $($user.OfficePhone) -departmentNumber $($user.departmentNumber) }
EDIT:
I tried the following using the "-Add" operator:
Import-Module ActiveDirectory
$users = Import-Csv -Path C:\users.csv
foreach ($user in $users) {
Get-ADUser -Filter "SamAccountName -eq '$($user.samaccountname)'" -Properties * |
Set-ADUser -Add #{departmentNumber = "$($user.departmentNumber)"}
}
And the following, using the "-Replace" operator:
Import-Module ActiveDirectory
$users = Import-Csv -Path C:\users.csv
foreach ($user in $users) {
Get-ADUser -Filter "SamAccountName -eq '$($user.samaccountname)'" -Properties * |
Set-ADUser -Replace #{departmentNumber = "$($user.departmentNumber)"}
}
Still no luck - do I have the syntax messed up?
I'm taking a quick look at the help for Set-ADUser: https://technet.microsoft.com/en-us/library/ee617215.aspx
I see a parameter for -Department, but not one for -DepartmentNumber
Will it work within your company's structure to just use -Department ?
For a custom attribute, you should be able to use the -Add parameter
-Add #{otherTelephone='555-222-1111', '555-222-3333'; otherMobile='555-222-9999' }
In order to use -Add or -Replace, you'll need to use a hashtable as your input instead of a string.
Here's a quick set of commands I used to convert a string into a single item hashtable:
$DeptNo = 'test'
$hash = #{}
$hash.Add('DepartmentNumber',$DeptNo)
$hash
Output from $hash:
Name Value
---- -----
DepartmentNumber test
I think you'll then be able to use -Add $hash to get it to do what you want.
Here is my code that got it working:
Set-ADUser -Identity $samName -Add #{'departmentNumber'="$UserDept"}
It is important to note you can only use -Add if nothing is there
otherwise use -Replace
$UserDept was a number but the quotes make it a string
and the attribute must have single quotes around it.

How can I update AD users using PowerShell and CSV import?

I'm trying to use this powershell script to update AD users. Ideally I'll be updating a bunch of attributes, but for now I'm just trying to get it to update the department just so I get tell if it's working.
Import-Module ActiveDirectory
$dataSource=import-csv "c:\ADupdate.csv"
foreach($dataRecord in $datasource) {
$employeeID=$dataRecord.employeeID
# List of attributes to update
$department=$dataRecord.department
Get-ADUser -SearchBase "ou=Test,ou=OurUsers,ou=Logins,dc=domain,dc=com" -Identity $employeeID -Properties department | Set-ADUser -Replace #{department=$department}
}
Figured out my own problem. Here is what I ended up using if anyone else is interested... though I'm using a lot of attributes.
Import-Module ActiveDirectory
$users = Import-Csv -Path c:\update.csv
foreach ($user in $users) {
Get-ADUser -Filter "employeeID -eq '$($user.employeeID)'" -Properties * -SearchBase "ou=Test,ou=OurUsers,ou=Logins,dc=domain,dc=com" |
Set-ADUser -employeeNumber $($user.employeeNumber) -department $($user.department) -title $($user.title) -office $($user.office) -streetAddress $($user.streetAddress) -City $($user.City) -state $($user.state) -postalCode $($user.postalCode) -OfficePhone $($user.OfficePhone) -mobile $($user.mobile) -Fax $($user.Fax) -replace #{"extensionAttribute1"=$user.extensionAttribute1; "extensionAttribute2"=$user.extensionAttribute2; "extensionAttribute3"=$user.extensionAttribute3}
}

How to switch to another domain and get-aduser

I am on a server under the DomainA. I can use Get-ADUser and it's working fine.
Now there is a trust built between DomainA and DomainB. I would like to switch to DomainB and get all the users that's in OU=New Users, DC=DomainB, DC=com.
I tried these but I get an error.
$FetchDomainB = Get-ADUser -SearchBase "OU=New Users, DC=DomainB, DC=com"
This asks me for Filter and i put in emailadress then it throws an error saying "Supplied distinguished name below to dc=DomainA,dc=net"
Same error is thrown for following code as well.
PS C:\> $test = Get-ADUser -SearchBase "dc=DomainB,dc=com" -filter {EmailAddress -like "*Smith_Karla*"} -Properties EmailAddress
Try specifying a DC in DomainB using the -Server property. Ex:
Get-ADUser -Server "dc01.DomainB.local" -Filter {EmailAddress -like "*Smith_Karla*"} -Properties EmailAddress
I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server argument.
$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
Get-ADUser -Server $dc.HostName[0] `
-Filter { EmailAddress -Like "*Smith_Karla*" } `
-Properties EmailAddress
get-aduser -Server "servername" -Identity %username% -Properties *
get-aduser -Server "testdomain.test.net" -Identity testuser -Properties *
These work when you have the username. Also less to type than using the -filter property.
EDIT: Formatting.
best solution TNX to Drew Chapin and all of you too:
I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server argument.
$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
Get-ADUser -Server $dc.HostName[0] `
-Filter { EmailAddress -Like "*Smith_Karla*" } `
-Properties EmailAddress
my script:
$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
Get-ADUser -Server $dc.HostName[0] ` -Filter { EmailAddress -Like "*Smith_Karla*" } ` -Properties EmailAddress | Export-CSV "C:\Scripts\Email.csv
You can try in multiple domains one after another using below script:
Here, first we check whether user is present in a domain and if so, we get the email address. Else we check in the subsequent domain.
$users = Get-Content D:\UserBase\users.txt
foreach($user in $users)
{
if([bool] (Get-ADUser -Filter { SamAccountName -eq $user } -Server DomainA.com))
{
Get-ADUser -Filter { SamAccountName -eq $user } -Server DomainA.com -Properties Mail |Select-Object -ExpandProperty Mail | Out-file D:\UserBase\emails.txt -Append
}
elseif([bool] (Get-ADUser -Filter { SamAccountName -eq $user } -Server DomainB.com))
{
Get-ADUser -Filter { SamAccountName -eq $user } -Server DomainB.com -Properties Mail |Select-Object -ExpandProperty Mail | Out-file D:\UserBase\emails.txt -Append
}
Also, you can get the list of domains in the organization using below script:
$ForestObj = Get-ADForest -Server $env:USERDOMAIN
foreach($Domain in $ForestObj.Domains) {
Get-ADDomainController -Filter * -Server $Domain | select Domain,HostName,Site
}