Powershell - Batch Rename of Home Server in HomePath - powershell

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
}

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?

Bult attribute edit in local AD

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.

PowerShell - Remove-ADGroupMember - Locking my admin account

I have the following line of code in a PowerShell file, intended to remove a user from all Active Directory groups beginning with an # symbol;
Get-ADGroup -Filter 'name -like "#*"' | Remove-ADGroupMember -Members $UserID
It actually works fine, and successfully removes them from the correct groups, however the script locks my admin account every time it's run. Weird!
From trawling the internet for a while, I suspect it's something to do with it 'using up' my Kerberos authentication tokens (it uses too many, as it runs for every single AD group beginning with #), or it thinks I'm trying to do something malicious because I'm sending such a large amount of commands in a short time?
Is there a way for me to amend this line of code, so that instead of running Remove-ADGroupMember for every single # group in the Active Directory, it only runs for the groups that the user is a member of? Or any other ideas?
Thank you.
Try this:
$groups = Get-ADPrincipalGroupMembership $user | where {$_.name -like "#*"} | select -expandproperty name
foreach($group in $groups){
Remove-ADGroupMember -identity $group -Members $user
}
It will only looking for the groups that the $user is a member in so you should be fine token wise.
Don't forget to change $user with user name or fill the variable beforehand.
Hmm, I don't have an AD infrastructure at home, but it looks like your example has nothing defining $UserID.

Using a global catalog in PowerShell

I have multiple domains in my forest, and I'm trying to write a script that will work with any user in the forest, so I'm using a global catalog in my script.
This works to retrieve the data, but when I try and modify the data I'm getting
Set-ADUser : The server is unwilling to process the request
If I use the domain controller (DC) as the server name, the modification completes as it should. I'd like to avoid writing a switch to set the server name. Is there anything else I can do here?
Get-ADUser $user -Server "contoso.local:3268" | %{Set-ADUser -Identity $_.distinguishedname -SamAccountName $_.SamAccountName -Server "contoso.local:3268"}
I'm not really clear on what you're trying to do here. Global catalog ports are read only (for LDAP).
If you want to make sure you find a domain controller that is a global catalog, you can use the following:
Get-ADDomainController -Discover -Service GlobalCatalog
Based on your comment, maybe what you need is $PSDefaultParameterValues:
$PSDefaultParameterValues = #{
"*-AD*:Server" = "contoso.local:3268"
}
Get-ADUser $user |
%{Set-ADUser -Identity $_.distinguishedname -SamAccountName $_.SamAccountName }

Powershell HomeDirectory not created on fileserver filesystem

I am having a weird problem using Powershell and setting a HomeDirectory via the cmdlet
Set-ADUser -Identity "user" -HomeDirectory "\\fileserver\home$\user"
Even though the cmdlet is working and setting the values in the AD, the necessary folder on the fileserver "\fileserver\home$\user" will not be created.
I have also unsuccessfully tried the same with the initial creation
New-ADUser -Name "user" -HomeDirectory "\\fileserver\home$\user"
I have started the Powershell on the Exchange server as domain-admin via UAC and imported the module ActiveDirectory via
Import-Module ActiveDirectory
Instead of using the UNC-path with NetBIOS-hostnames I also tried the FQDN \fileserver.domain.local\ and also the ip adrress \ip\
If I am using the cd command to enter the UNC-path via Powershell, it does also work, I can also create directories.
cd \\fileserver\home$
mkdir test_dir
Still, the directory will not be created.
If I am using the AD GUI, and try to alter the HomeDirectory-path, the folder will be created.
Any hints?
Many thanks
PS: 2008R2 x64, Exchange 2010, 1x Exchange, 1x AD controller, 1x fileserver
It is worth mentioning the following from Hey, Scripting Guy! Blog
Remember, all we have done is edit a field in Active Directory. The
file system on the foreign server has no clue about the information
presented within Active Directory. When you edit those fields in the
GUI, the user folder and permissions are provisioned as a function of
the code within that GUI interface—they are not a function of Active
Directory.
Much like Paul suggested I think you just need to create the folder yourself. Linked in that article is information about setting permissions for the file share as well. I imagine you already have that done.
NEW-ITEM –path "\\fileserver\home$\user" -type directory -force
This is the best way to do this will be to create home folder for all users if doesn't exist. Create a schedule task with event id 4720 to do this automatically
Connect home folder path and drive letter.
Get-ADUser -filter * | % { Set-ADUser $_ -HomeDrive "H:" -HomeDirectory ('\\server\home$\' + $_.SamAccountName) }
create home folders for each users:-
ForEach( $User in (Get-ADUser -filter * | if( -not ( -HomeDrive "H:" -HomeDirectory ('\\server\home$\' + $_.SamAccountName) )