Powershell command to replace AD user's title in title field not working? - powershell

I have created a script for a project with some code which I was given fused with my own. Most of the commands which are great, but unfortunately two commands are not working.
These commands are:
Set-ADUser $UserName -replace #{title="Former Employee" + $title}
Move-ADObject -Identity $UserName -TargetPath "OU=Former Employee,OU=Users,OU=Contoso,DC=Contoso,DC=local"
Any ideas? I appreciate the help!
Here is the full script:
$UserName = Read-Host "Please enter username to be disabled"
if ($UserName) {
''
} Else {
'User not Found'
}
Disable-ADAccount $UserName
Get-ADUser $UserName -Properties MemberOf | ForEach-Object {
$_.MemberOf | Remove-ADGroupMember -Members $_.DistinguishedName -Confirm:$false }
$title = get-aduser $UserName -properties title
$title = $title.title
$old=Get-ADuser $UserName -properties Description
$old = $old.description
$new = "DISABLED " + $old
set-aduser $UserName -description $new
set-aduser $UserName -clear "manager"
set-aduser $UserName -clear "telephonenumber"
# these two:
set-aduser $UserName -replace #{title="Former Employee" + $title}
Move-ADObject -Identity $UserName -TargetPath "OU=Former Employee,OU=Users,OU=Contoso,DC=Contoso,DC=local"

I think it's better to clear up a bit of your code. Have a look at this:
$SamAccountName = Read-Host 'Please enter the SamAccountName of the user you want to disable'
$VerbosePreference = 'SilentlyContinue'
$VerbosePreference = 'Continue'
Try {
$ADUser = Get-ADUser -Identity $SamAccountName -Properties MemberOf, Title, Description
Write-Verbose "User '$($ADUser.Name)' found in AD"
}
Catch {
throw "No user found in AD with SamAccountName '$SamAccountName'"
}
Write-Verbose 'Disable user'
Disable-ADAccount $ADUser
foreach ($Group in $ADUser.MemberOf) {
Write-Verbose "Remove user from group '$Group'"
Remove-ADGroupMember -Identity $Group -Members $ADUser -Confirm:$false
}
$NewTitle = "Former Employee {0}" -f $ADUser.Title
Write-Verbose "Set 'Title' to '$NewTitle'"
Set-ADUser -Identity $ADUser -Title $NewTitle
$NewDescription = "DISABLED {0}" -f $ADUser.Description
Write-Verbose "Set 'Description' to '$NewDescription'"
Set-ADUser -Identity $ADUser -Description $NewDescription
foreach ($Property in #('Manager', 'telephonenumber')) {
Write-Verbose "Clear property '$_'"
Set-ADUser -Identity $ADUser -Clear $Property
}
$NewTargetPath = "OU=Former Employee,OU=Users,OU=Contoso,DC=Contoso,DC=local"
Write-Verbose "Move AD User to '$NewTargetPath'"
Move-ADObject -Identity $ADUser -TargetPath $NewTargetPath
Some tips:
Use Write-Verbose to show what is happening in the script. Yuo can disable/enable this by commenting out the VerbosePreference.
Always start with retrieving an object instead of working with text strings ($UserName vs $ADUser). See Get-ADUser as the very first action.
Work with Try/Catch in case things fail.
Always use the parameter names. It makes it more clear on what you're trying to do.

Related

List of Active Directory groups not showing from PowerShell code

I input a list of groups for each user in CSV, and tried to create users using PowerShell code.
This is the PowerShell code:
- name: Change group for AD users
ansible.windows.win_powershell:
script: |
[CmdletBinding()]
param (
[array]
$datalist
)
$output = foreach ($user in $datalist) {
$name = $user.SamAccountName
$groups = $user.Groups
$users = Get-ADUser -Filter "SamAccountName -eq '$name'"
Get-ADUser -Filter "SamAccountName -eq '$name'" -Properties MemberOf | ForEach-Object {$_.MemberOf | Remove-ADGroupMember -Members $users -Confirm:$false}
Add-ADGroupMember -Identity $groups -Members $users
}
parameters:
datalist: "{{ hostvars.localhost.list }}"
I ended up getting this error:
"message": "Cannot convert 'System.Object[]' to the type 'Microsoft.ActiveDirectory.Management.ADGroup' required by parameter 'Identity'. Specified method is not supported."
Also tried '$groups':
"message": "Cannot find an object with identity: '$groups' under: 'DC=adexample,DC=local'.",
And "$groups":
"message": "Cannot find an object with identity: 'CN=GroupA,OU=Groups,DC=adexample,DC=local CN=Test Group,OU=Groups,DC=adexample,DC=local' under: 'DC=adexample,DC=local'.",
This is how I input my list of groups into the CSV file:
Groups
CN=GroupA,OU=Groups,DC=adexample,DC=local;CN=Test Group,OU=Groups,DC=adexample,DC=local
CN=GroupA,OU=Groups,DC=adexample,DC=local;CN=Test Group,OU=Groups,DC=adexample,DC=local
What is the right way to write $groups so that my list of groups can be output correctly?
Updated with CSV in plain text:
FirstName,SamAccountName,path,UserPrincipalName,Groups
Greg,gre.b87,"OU=Temporary Users,DC=adexample,DC=local",gre.b87#gmail.com,"CN=GroupA,OU=Groups,DC=adexample,DC=local;CN=Test Group,OU=Groups,DC=adexample,DC=local"
Zee,zeef.cd,"OU=Temporary Users,DC=adexample,DC=local",zeef.cd#gmail.com,"CN=GroupA,OU=Groups,DC=adexample,DC=local;CN=Test Group,OU=Groups,DC=adexample,DC=local"
I adapted bhuvanachand komara's to mine and it worked for me:
$output = foreach ($user in $datalist) {
$name = $user.SamAccountName
$groups = $user.Groups -split ";"
Get-ADUser -Filter "SamAccountName -eq '$samname'"
$users = Get-ADUser -Filter "SamAccountName -eq '$samname'"
foreach ($group in $groups) {
Add-ADGroupMember -Identity $group -Members $user
}
Get-ADUser -Filter "SamAccountName -eq '$samname'" -Properties MemberOf | ForEach-Object {$_.MemberOf | Remove-ADGroupMember -Members $users -Confirm:$false}
}
The main thing is that I need to add $groups = $user.Groups -split ";" and another foreach loop for the groups.
$csvFile = 'path\to\csv\file.csv'
$users = Import-Csv -Path $csvFile
foreach ($user in $users) {
$samAccountName = $user.SamAccountName
$givenName = $user.GivenName
$surname = $user.Surname
$password = $user.Password
$email = $user.Email
$groups = $user.Groups -split ","
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
New-ADUser -SamAccountName $samAccountName -GivenName $givenName -Surname $surname -DisplayName "$givenName $surname" -EmailAddress $email -AccountPassword $securePassword -Enabled $true
foreach ($group in $groups) {
Add-ADGroupMember -Identity $group -Members $samAccountName
}
}
Example CSV
SamAccountName,GivenName,Surname,Password,Email,Groups
user1,chand,komara,Password1,user1#example.com,group1,group2
user2,bhuvan,unnava,Password2,user2#example.com,group2,group3
For each user in the $users array, the code creates a new Active Directory user using the New-ADUser cmdlet with the specified SamAccountName,
GivenName, Surname, DisplayName, EmailAddress, and account password.
It then adds the user to the specified groups using the Add-ADGroupMember cmdlet.

Get-ADUser manager email field blank

I wrote this code which works except for when I tried to add this: -and '$($user.'Manager Email' -notlike '')' to the end of the Get-ADUser Manager section which causes it to fail. What I would like to accomplish is to leave the Manager field blank in AD if the "Manager Email" field is blank within the CSV file. Any help would be greatly appreciated.
$Users = Import-CSV C:\AD-Test\HROrgData202207_2.csv
foreach ($User in $Users)
{$AdUser = Get-ADUser -Filter "EmailAddress -eq '$($user.'Business Email')' -and Enabled -eq '$True'" -Properties mail -ErrorAction SilentlyContinue
$manager = Get-ADUser -Filter "EmailAddress -eq '$($user.'Manager Email')' -and '$($user.'Manager Email' -notlike '')'" -Properties mail -ErrorAction SilentlyContinue
if ($adUser) {
Set-ADUser -Identity $ADUser -Department $user.Department -Title $user.Job -Office $user.Location -Description $user.Position -EmployeeID $user.'Employee ID' -Company $user.'Legal Entity' -Manager $manager
}
else {
Write-Warning "User $($User.'Business Email') could not be found"
}

Powershell Import-Csv then Get-Aduser results in all users in ad being displayed when a Blank Line appears

I am writing a powershell script to disable users due to the fact that we get a list of them everyday and it is monotonous. I paste the list from the ticket into a csv formatted as Lastname, Firstname then run my script with imports the list, serches ad and ask if you want to disable if it finds them. Here is the code...
# Set variables
$Import = "C:\Scripts\Support Files\Users_To_Disable.csv"
$Export = "C:\Scripts\Support Files\Disabled_Users_Output.txt"
# Import user list
$Users = Import-CSV $Import
foreach ($User in $Users)
{
# Set user variables
$LastName = $User.("Surname")
$FirstName = $User.("GivenName")
# Use user variables from list to search ad
$UserName = (Get-ADUser -Filter "GivenName -like '$FirstName*' -and Surname -like '$LastName*'").SamAccountName
# What to do if it finds nothing
If ($UserName -eq $Null)
{
Write-Host $LastName, $FirstName NA -ForegroundColor Yellow
Write-Output "$LastName, $FirstName NA" | Out-File $Export -Append
}
# What to do if it finds a user
Else
{
# Ask for user input
Write-Host $LastName, $FirstName Found -ForegroundColor Green
Write-Host UserName = $UserName -ForegroundColor Green
DO {
$Disable = Read-Host "Do you want to disable user? (Y/N)"
If($Disable -eq "Y")
{
# Disable the user
Disable-ADAccount -Identity $UserName
# Move the user
Get-ADUser $UserName | Move-ADObject -TargetPath "OU=Disabled - Retention,DC=intranet,DC=sw"
# Add Disabled Users group
Add-ADGroupMember "Disabled Users" -Members "$UserName"
# Set Disable Users as primary group
$Group = Get-ADGroup "Disabled Users" -Properties #("PrimaryGroupToken")
Get-ADUser "$UserName" | Set-ADUser -Replace #{PrimaryGroupID=$Group.PrimaryGroupToken}
# Remove all other groups
$User = Get-ADUser "$UserName" -Properties MemberOf
$Groups = $User.MemberOf |ForEach-Object { Get-ADGroup $_ }
$Groups | ForEach-Object { Remove-ADGroupMember -Identity $_ -Members $User -Confirm:$false }
# Output
Write-Host $LastName, $FirstName Disabled -ForegroundColor Red
Write-Output "$LastName, $FirstName Disabled" | Out-File $Export -Append
Break
}
}
Until ($Disable -eq "N")
}
}
Invoke-Item $Export
All of that works, what is scary is that if there are blank cells above a user then it returns all of the users in ad and asks if you want to disable all of them. In other words if the csv looks like this...
Surname GivenName
User Test
Everything works fine, but if it looks like this...
Surname GivenName
User Test
Pandemonium, well not really but it does ask if you want to initiate a resume generating event, which I don't so how can I build in some safety that would stop it from returning all of ad when there are blanks in the csv before users?
You can eliminate the blank lines by filtering out Null values on your import, which should resolve the problem.
$Users = Import-CSV $Import | Where-Object {$_.Surname}

Powershell get-content, foreach

I've written a Powershell script to prompt for an Active Directory username, and then add the user to relevant AD groups based on which email server the mailbox is hosted on.
This works great but I'm looking to automate this even further by importing a list of AD usernames from a text file. I've been looking at Get-Content and Foreach but not having much success.
Can anyone show me the correct methods please?
$list = Get-Content "C:\users.txt"
Foreach ($user in $list) {
#Original code to prompt
#$user = Read-Host -Prompt 'Input the username'
Add-ADGroupMember -Identity "Staff" -Member $user
$HomeMDB = Get-ADuser $user -Properties * | Select *HomeMDB*
if ($HomeMDB -like '*Email_Ser1*') {
Add-ADGroupMember -Identity "Email_Server1" -Member $user
}
if ($HomeMDB -like '*Serv2*') {
Add-ADGroupMember -Identity "Email_Server2" -Member $user
}
if ($HomeMDB -like '*Serv_Exchange3*') {
Add-ADGroupMember -Identity "Email_Server3" -Member $user
}
}
Write-Host "--------------------------------------------"
Write-Host $user "Exchange Mailbox Store::: $HomeMDB "
Write-Host "--------------------------------------------"
Read-Host -Prompt 'Press Enter to Exit'
exit
The script looks fine. I would like to suggest you to give the input file in below format (One below the other)
user1
user2
user3
Hope this helps!

If And statement with a foreach for AD Users in Powershell

$names = Import-CSV C:\PowerShell\TerminatedEmployees.csv
$Date = Get-Date
foreach ($name in $names)
{
Get-ADPrincipalGroupMembership -Identity "$($name.TextBox37)" | select Name | Out-File "C:\Powershell\ADUserMemberships\$($name.TextBox37)Memberships.txt"
$ADgroups = Get-ADPrincipalGroupMembership -Identity "$($name.TextBox37)" | where {$_.Name -ne "Domain Users"}
Remove-ADPrincipalGroupMembership -Identity "$($name.TextBox37)" -MemberOf $ADgroups -Confirm:$false
Disable-ADAccount -Identity "$($name.TextBox37)"
Get-ADUser -Identity "$($name.TextBox37)" | Move-ADObject -TargetPath "OU=DisabledAccounts,OU=XXX,DC=XXX,DC=XXXX,DC=XXX"
Set-ADUser -Identity "$($name.TextBox37)" -Description "Disabled $Date"
}
This is an already working script I have. However, I realized I need to check 2 properties on the AD user to determine if they need to need to go through my foreach statement. Both properties need to be met. If they are then there's no reason for the AD users to be processed.
The AD user is already disabled.
The AD user already resides in the Disabled OU.
I'm thinking this needs to be done in an If -And statement. But does this need to be done before the foreach or inside the foreach?
Start out by retrieving the user account with Get-ADUser and then inspect the Disabled property + compare the Disabled OU to the DistinguishedName of the user:
$names = Import-CSV C:\PowerShell\TerminatedEmployees.csv
$Date = Get-Date
$DisabledOU = "OU=DisabledAccounts,OU=XXX,DC=XXX,DC=XXXX,DC=XXX"
foreach ($name in $names)
{
$ADUser = Get-ADUser -Identity "$($name.TextBox37)"
if(-not($ADUser.Enabled) -and $ADUser.DistinguishedName -like "*,$DisabledOU")
{
# no need to proceed, skip to next name in foreach loop
continue
}
$ADGroups = Get-ADPrincipalGroupMembership -Identity "$($name.TextBox37)"
$ADGroups |Select-Object Name |Out-File "C:\Powershell\ADUserMemberships\$($name.TextBox37)Memberships.txt"
# no need to call Get-ADPrincipalGroupMembership again
$ADgroups = $ADGroups | where {$_.Name -ne "Domain Users"}
Remove-ADPrincipalGroupMembership -Identity "$($name.TextBox37)" -MemberOf $ADgroups -Confirm:$false
Disable-ADAccount -Identity "$($name.TextBox37)"
$ADUser | Move-ADObject -TargetPath $DisabledOU
Set-ADUser -Identity "$($name.TextBox37)" -Description "Disabled $Date"
}