I am having an issue with this script. I am using it to look for certain users in an OU on AD and change the email address field to something I want. However, once I run the command, it chooses all of users with empty emails correctly, but seems to have replaced them all with the same email address, let's say "brubble#domain.com".
I need to target the ones with that email address now, and change them to the appropriate email address, but it just keeps changing it to "brubble#domain.com".
$SearchBase = "OU=Dead Accounts,DC=Domain,DC=Domain,DC=COM"
$Filter = {EmailAddress -notlike "*"}
get-ADUser -Filter $Filter -SearchBase $SearchBase -Properties emailaddress | ForEach-Object {
Write-Host $_.EmailAddress
$newEmail = $_.samaccountname + "#esilicon.com"
Set-Aduser $($_.SamAccountName) -EmailAddress $newEmail
}
Related
I need to change a lot of users "email" field on their active directory profile however I cant seem to find the answer Im looking for looking at other posts.
I`m quite new to powershell but I've landed this task to be done at work.
The email address format is in the style of "first name" and "lastname" seperated by a "." with the domain appended on the end naturally.
An example would be John.Doe#domain.com
How would I go about this with powershell with users in 6 different OUs but all under the same root OU?
Kind regards
It depends on how you have the data. If you already have the emails in say a csv with a column titled "OldEmail" and "NewEmail" you could do something like:
$csv = import-csv \\path\to\csv
foreach($user in $csv) {
get-aduser -filter {mail -eq $user.OldEmail} | Set-ADUser -EmailAddress $user.NewEmail
}
You could do something like below, but as always when changing stuff in Active Directory,
try it out on a bunch of testusers first
# enter the root OU DistinguishedName where the sub OU's are here
$rootOU = "OU=Users,DC=yourdomain,DC=com"
# Get a list of user objects that do not have an email address in 'firstname.lastname#yourdomain.com' format.
# you only have to ask for property EmailAddress (LDAP name is 'mail'), because these properties are returned by default:
# DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID, Surname, UserPrincipalName
Get-ADUser -Filter * -SearchBase $rootOU -SearchScope Subtree -Properties EmailAddress |
Where-Object { $_.EmailAddress -ne ('{0}.{1}#yourdomain.com' -f $_.GivenName, $_.Surname) } |
ForEach-Object {
$mail = '{0}.{1}#yourdomain.com' -f $_.GivenName, $_.Surname
Write-Host "Setting up email address $mail for user $($_.SamAccountName)"
$_ | Set-ADUser -EmailAddress $mail
}
Import-CSV "C:\users\Balbahagw\desktop\test1.csv" |
Foreach-Object {
$aduser = Get-ADUser -Filter { EmailAddress -eq $_.'EmailAddress' }
if( $aduser ) {
Write-Output "Adding user $($aduser.SamAccountName) to groupname"
Add-ADGroupMember -Identity tech-103 -Members $aduser
} else {
Write-Warning "Could not find user in AD with email address $($_.EmailAddress)"
}
}
Script is working now, however it can't find the user in AD with the email address.
You need to first resolve the ADUser object matching that email address, the -Identity parameter won't auto-resolve based on the EmailAddress field of an ADUser. Assuming the EmailAddress property is set appropriately on the user object in AD, and assuming the column name for the email address in your CSV is ExternalEmailAddress, this should work:
Import-CSV "C:\users\user\desktop\test1.csv" | Foreach-Object {
$aduser = Get-ADUser -Filter "EmailAddress -eq '$($_.EmailAddress)'"
if( $aduser ) {
Write-Output "Adding user $($aduser.SamAccountName) to groupname"
Add-ADGroupMember -Identity groupname -Members $aduser
} else {
Write-Warning "Could not find user in AD with email address $($_.EmailAddress)"
}
}
Note that if the ADUser does not have the email address set, you will not be able to match that AD user to an email.
Here are the docs for Add-ADGroupMember, you may want to read up on them for more information: https://learn.microsoft.com/en-us/powershell/module/activedirectory/add-adgroupmember?view=winserver2012-ps&viewFallbackFrom=winserver2012r2-ps
EDIT: Found some strangeness with using brackets and the $PSitem, so I changed it to use a string-based filter.
EDIT 2: Found the cause for why using a variable in a bracket-based -Filter doesn't work (which is how I had originally written this), and in fact is not recommended when scripting: Get-Aduser -Filter will not accept a variable
Import-Module ActiveDirectory
Get-ADUser -SearchBase "OU=CompanySite,DC=example,DC=domain,DC=com" -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} -Properties "SamAccountName","msDS-UserPasswordExpiryTimeComputed", "Department", "Title", "Manager" |
Select-Object -Property "SamAccountName", #{Name="Password Expiry Date"; Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}; #{Label="Manager";Expression={(Get-aduser -filter {sAMAccountName -eq $_.Manager}.sAMAaccountName)}};# |
Export-Csv "C:\Update\PasswordExpired.csv" -NoTypeInformation
I am trying to get an CSV that contains the employees whose password is expiring and get their managers name, the employees job title, the employees name and the date the password will expire.
However when I run this, I am getting the employees name and date the password is expiring. No other fields. I dont understand where I went wrong
Ok, there were a few errors causing issues:
You had a semi-colon (;) after the Password Expiry Date property in the Select-object portion. This caused the code to terminate at that point. It should be a comma.
For the Manager property, your expression is incorrect. You have your end parentheses after SamAccountName. It should be before the period. Additionally you are trying to match the DN with the SamAccountName data so it will return nothing. Just do a Get-ADUser and set the identity as the $_.Manager output. From there you can use the parentheses to output whatever metadata you want from the full ADUser Object for the manager. You can swap out SamAccountName to DisplayName or something else.
Your code: (Get-ADUser -filter {SamAccountName-eq $_.Manager}.SamAccountName)
Correct code: (Get-ADUser $_.Manager).SamAccountName
Title and Name are not included because you aren't calling them in the Select-object code. The "-Properties" section of Get-ADUser only adds the attribute to the list of retrieved attributes. What you set in Select is what is output to the screen or file.
You had a comment (#) tag before the Export-CSV section so that wasn't running either.
Here's the code. I don't have the manager attribute in my AD so I wasn't able to validate that section, but the rest ran correctly. I've also made it a bit more transportable. The SearchBase is now specified in a variable, as is the export location for the file. Additionally, you don't need to specify SamAccountName in the -Properties section as this is a default attribute for Get-ADUser.
Import-Module ActiveDirectory
$SearchPath = "OU=CompanySite,DC=example,DC=domain,DC=com"
$ExportPath = 'C:\Update\PasswordExpired.csv'
$Users = Get-ADUser -SearchBase $SearchPath -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False} -Properties "msDS-UserPasswordExpiryTimeComputed", "Department", "Title", "Manager"
$Users | Select-Object -Property Name,"SamAccountName",Title,#{Name="Password Expiry Date"; Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}},#{Label="Manager";Expression={(Get-ADUser $_.Manager).sAMaccountName}} | Export-Csv $ExportPath -NoTypeInformation
I am new to powershell and need to search for special accounts like a developer (dev-) or admin (ad-), strip the prefix off and see if that user has an account (sAMAccountName)
Below, I am able to serach and get all the special account from my domain, but I need to script the entire process so I only get back the special accounts that do not have regular user accounts.
ForEach ($acct in "Dev-*","dev-*","rl-*","cafe-*","dev-dev-*","ad-*", `
"sa-*","AD-*","ir-*","tst-*","o365-*","te-*","la-*","vmtest-*", `
"mtep-*","EIM-*","GRT*","cbl-","DS-*","fim-*") {
Get-ADUser -Filter {sAMAccountName -like $acct} -SearchBase "DC=xxx,DC=xxx,DC=com" `
-Properties sAMAccountName | Select sAMAccountName
}
It's not pretty, but you could remove the prefix for the username that you find and search for that user. If nothing returns (no match), continue with the dev-account, else drop it. Ex:
ForEach ($acct in "Dev-*","dev-*","rl-*","cafe-*","dev-dev-*","ad-*", "sa-*","AD-*","ir-*","tst-*","o365-*","te-*","la-*","vmtest-*", "mtep-*","EIM-*","GRT*","cbl-*","DS-*","fim-*") {
Get-ADUser -Filter {sAMAccountName -like $acct} -SearchBase "DC=xxx,DC=xxx,DC=com" |
Where-Object {
$prefix = $acct.Replace("*","")
$user = $_.sAMAccountName.Replace($prefix,"")
if(-not(Get-ADUser -Filter {sAMAccountName -eq $user} -SearchBase "DC=xxx,DC=xxx,DC=com")) {
#Throw user further down the pipeline
$_
}
} |
Select sAMAccountName
}
I'm trying to get a Users Managers Email from AD with Powershell, so i want to enter UserA and get return AManager#domain.com. so i can reset a user password and have it email the password to the manager specified in AD. so, here is waht i got:
Get-ADUser -Identity SAMAccountName -Properties EmailAddress,Manager | Select-Object { (Get-AdUser $_.Manager -Properties EmailAddress).EmailAddress }
but, its returning it like a table format like this:
(Get-ADUser $_.Manager -Properties EmailAddress).EmailAddres
------------------------------------------------------------
ManagersEmail#myDomain.com
So i cannot use that as a valid email, is there a way to get just the email address. Thnaks for any help.
This worked for me if I understand what you want:
Get-ADUser -Identity SAMAccountName -Properties EmailAddress,Manager | %{(Get-AdUser $_.Manager -Properties EmailAddress).EmailAddress}