Bult attribute edit in local AD - powershell

I'm trying to find a PowerShell script that updates the title attrubute in AD for a large number of users. I was hoping to find a script that imports the changes from a csv file and updates the atribute only for the users in the list. I found the below script but apparently it is working only for Azure AD, and I need it for the local AD. Perhaps someone more switche on than me can help me amend the below script.
#Import Active Directory module
Import-Module ActiveDirectory
#Import CSV File to set variable for the user’s logon name + update data + delimiter
$Users = Import-CSV -Delimiter ";" -Path "c:\psscripts\users.csv"
#Using your code to filter AD Sam Accounts listed CSVData is listed with the information you wish to update
Foreach($user in $users){
#Using your code to filter AD Sam Accounts Based on column samaccountname in the csv file
Get-ADUser -Filter "SamAccountName -eq '$($user.samaccountname)'" | Set-ADUSer `
-title $($User.Title)`
}

That code is fine, beyond some variable consistency and lack of checks, and does target local AD, though use of that deliminator would likely be unusual if you're just using a standard csv file. If you have the data in an excel document with the column headers of "SamAccountName" (typically email addresses) and "Title", and then save the file as a csv, the below amended code should work for you. Added logic to test for blank Title, as you can't assign a blank value to an attribute.
#Import Active Directory module
Import-Module ActiveDirectory
#Import CSV File with AD SAM account and Title data from users.csv in the C:\psscripts directory of your computer
$Users = Import-CSV -Path "c:\psscripts\users.csv" | Where {$_}
#Filter AD Sam Accounts listed in CSV and update title for listed accounts
Foreach($user in $Users){
#Check for value of $user.Title in case of null value
If ($user.Title){
#Filter AD Sam Accounts Based on column SamAccountName in the csv file and update the account Title field
Get-ADUser -Filter "SamAccountName -eq '$($user.SamAccountName)'" | Set-ADUSer -Title $($user.Title)
}
else {
#Filter AD Sam Accounts Based on column SamAccountName in the csv file and clear the account Title field
Get-ADUser -Filter "SamAccountName -eq '$($user.SamAccountName)'" | Set-ADUSer -clear -Title
}
}
I'd recommend testing it on a test user account or two before going whole hog on your actual list. Goes without saying that you need to be logged into a PS session as a domain account with adequate privileges to make the changes to the accounts when running the script. VS Studio Code is a good environment to work in, and you can launch the program as the elevated account (shift + right-click program icon, choose run as a different user) within your normal account environment, to sandbox the privileges to just what you're working on in VS Studio Code.
If you are trying to work in Azure AD, you'd need to add these lines and approve your account access request within Azure, depending on your tenant setup, to actually run the script successfully. Depending on the tenant configuration, this may be required in a hybrid AD/Azure AD environment regardless of your intent to apply to local AD.
Connect-MgGraph -Scopes "User.ReadWrite.All", "Directory.ReadWrite.All"
Select-MgProfile -Name "beta"
Best regards, no warranties given or implied, please accept as answer if this works for you.

Related

Specifying a list of usernames to be deleted from AD via powershell

I was wondering if you could help me.
I was hoping you could assist me in creating a script where I would specify a list of usernames (could be either in .txt or csv file) to be deleted from AD in PowerShell.
I know there is command to do this but I have to change the username every time I run the command:
Remove-ADUser Username
Thanks for your assistance guys.
UPDATE 1
Can you stop changing the question (I would prefer help instead!)
I am looking into this myself and will attempt to answer the question (I am still learning so be patient!).
I have come up with a script:
$users=Get-Content -Path C:\Users\Me\Desktop\disableusers.txt
ForEach ($user in $users)
{
Remove-ADUser -identity $user
}
I know its not the most slickest of scripts but if it does the job I am happy.
I have also found something like this:
$Users = Import-Csv 'c:\temp\yourcsv.csv'
Foreach ($User in $Users)
{
Try
{
# Verify that users from your CSV exist in Active Directory
Get-ADUser $User -ErrorAction Stop | Out-Null
Remove-ADUser $User -Confirm:$False
}
Catch
{
  Write-Host "Username '$User' not found in Active Directory"
}
}
But the above script must take this into consideration:
Depending how your csv looks like you might need to change $User to $User.SamAccountName or whatever that column is named in your csv.
UPDATE 2
I tried to do the CSV method but I get error stating it can't find the usernames.
I tried with CSV only containing usernames and altering the script and also with the field header of SamAccountName, I know this will sound stupid but once I have a field header of SamAccountName does that mean all $Users and now $User.SamAccountName in the CSV script?

Update Job Descriptions in AD using Email Addresses Using PowerShell

I am currently attempting to write a powershell script that will update the Job Description of Various Users in Active Directory via a CSV File
The identifier I have been given to use is the User's Email Address instead of Username (Which I think would of been easier!)
Can anyone assist as I am struggling to write anything effective that works! :(
Ok, suppose your .csv looks like this:
"email","jobtitle"
"user1#mydomain.com","New job description for user1"
"user2#mydomain.com","New job description for user2"
"user3#mydomain.com","New job description for user3"
you could then do something like
Import-Module ActiveDirectory
Import-CSV -Path <PATH-TO-YOUR-CSV-FILE> | Foreach-Object {
# properties from the csv
$mail = $_.email
$title = $_.jobtitle
Get-ADUser -Filter {(mail -eq "$mail")} | Set-ADUser -Title $title
}

Powershell results different based on save location

I am using powershell to extract all users from an OU who have not signed into their account in 365 number of days.
import-module activedirectory
get-aduser -SearchBase 'ou=staff,ou=brummitt,dc=DUNELAND,dc=LOCAL' -filter 'enabled -eq $true' -Properties samaccountname,lastlogondate |
Where-object {$_.lastlogondate -lt (get-date).AddDays(-365)} |
Select-Object -ExpandProperty samaccountname >>'C:\stale\brummitt.txt'
In attempt to organize the folder these are stored in I have created a folder in my servers C: drive called stale and have a folder called scripts in which the powershell scripts are stored.
When I run the script with powershell and the save extension is C:\stale\brummitt.txt it outputs all users in that OU. When the save location is C:\brummitt.txt it returns the correct users who have not signed in for over a year. Why would the results be changing based on the save location and how can this be combated?
Added:
I am running the powershell script from within the scripts folder.
Did you try using Tee-Object as a part of the pipeline?, that will give you the opotunity to check the stream to the file on console,

Powershell - Batch Rename of Home Server in HomePath

Admittedly, I am not a PowerShell monster, so I'm going to punt...
I am working with a client who is pulling a list of all his user shares on his CIFS server to help redirect AD HomeDirectory paths in a major file server migration. This list is being compared to the list of AD users home directories as AD currently sees them.
The problem is that some user directories use old NT Usernames (NAMEI$) and some use SAMAACCOUNTNAME$. To Additionally complicate, the share SERVER differs in AD due to an elaborate history of DNS aliases over the past 10-15 years - so even though all the users home directories currently exist on SERVERA they could be mapped to OLDSERVER3, OLDERSERVER01, or OLDESTSERVERNT4 - resulting in home directories that are all over the map.
I need to write a script that can use the SAMACCOUNTNAME from a list, then change all the server information in the home directory to \NEWSEVERNAME\CURRENTSHARE$ - hopefully using something like this:
Use UserList
From UserList, get-ADuser -Identity $_ -HomeDrive "U:" -HomeDirectory
in HomeDirectory replace \\*\ with \\NewServer\ while leaving the Share$ untouched.
Set-ADuser -Identity $_ -HomeDrive "U:" -HomeDirectory
I'm fairly certain that this can be accomplished with regular expressions, for/each loops, etc... but I can't put it together.
Thank you for your help!
I went through the same migration a short while ago. Here is what you can use to set the new server while leaving the share folder untouched.
Import-Module activedirectory
$samAccountNameList = get-content "c:\userIds.txt"
$newServer = "newFps01"
foreach ($user in $samAccountNameList) {
$adProperties = get-aduser -Identity $user -Properties homeDirectory, homeDrive
$homeDrive = $adProperties.HomeDrive
# Split original homedirectory path and grab just the share folder portion
$shareFolder = ($adProperties.homeDirectory).Split("\")[3]
$newHomeDirectory = "\\$newServer\$shareFolder"
set-aduser -Identity $user -HomeDrive $homeDrive -HomeDirectory $newHomeDirectory
}

powershell script Ad script group

I have the below ps script to Import users details from a domain/ forest from a domain local group, everything is working, but i need to include two more details, user mail is and user domain in the excel. How can I do this?
Get-ADGroupMember "test" | Select-Object samaccountname, name, distinguishedname | Export-CSV -path "c:\test.csv" -notypeinformation
Some properties are not included in the default property set of a user object. In that case you need to query the user with the additional (or all) properties, e.g.:
Get-ADGroupMember "test" `
| Get-ADUser -Properties * `
| select samaccountname, name, distinguishedname, mail `
| Export-CSV "C:\test.csv" -NoTypeInformation
AFAIK the (DNS) domain name is not an AD attribute, but you could derive it from the distinguished name:
(Get-ADUser "name").distinguishedName -replace '^.*?,dc=' -replace ',dc=', '.'
so you could add another property in the select statement like this:
#{n="domain";e={$_.distinguishedName -replace '^.*?,dc=' -replace ',dc=', '.'}}
As for the referral error: the group seems to be containing members from another domain. AFAIK all of the following requirements must be met to be able to run AD PowerShell cmdlets against other domains in the same forest:
The Active Directory Web Services must be running on at least one of the DCs of the remote domain, and the port must be accessible from the local domain.
Your account must have admin privileges on the remote DCs (e.g. by being a member of the Enterprise Admins group).