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

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}

Related

Move list of users from one OU to a different OU and disable them at the same time - Powershell

I currently have a script that is able to disable a list of usernames using a text file which has a list of username specified:
$users = Get-Content C:\disableusers.txt
foreach ($user in $users) {
Disable-ADAccount -Identity $user
Write-Host "user $($user) has been disabled"
}
I was wondering if it is possible to incorporate moving using from one OU to another during the execution of this script?
e.g. moving from "Users" OU to "Disabled Users" OU.
I have created another script which does move a list of usernames to "Disabled Users" OU:
$users=Get-Content C:\disableusers.txt
$OU = "distinguishedName of my Disable Users OU"
foreach ($user in $users) {
Get-ADUser $user | Move-ADObject -TargetPath $OU
}
Any help on this is much appreciated thanks.
Both of your snippets look good to me, if you are interested in combining them into one you could use -PassThru from Disable-ADAccount to pass the disabled object through the pipeline to Move-ADObject:
$OU = "distinguishedName of my Disable Users OU"
Get-Content C:\disableusers.txt | ForEach-Object {
try {
Disable-ADAccount $_ -PassThru |
Move-ADObject -TargetPath $ou
Write-Host "user $($user) has been disabled and moved"
}
catch {
Write-Error $_
}
}

Replace AD attribute value with csv file header values

I want to replace AD attribute "userPrincipalName" value according to CSV file header value
here is what csv file(group.csv) contains
sAMAccountName
--------------
test.user1
test.user2
below the script
$data = Import-Csv -Path .\group.csv -Header 'sAMAccountName'
foreach($user in $data){
Get-ADUser -Filter {sAMAccountName -eq "$($user.sAMAccountName)"} | Set-ADUser -Replace #{userPrincipalName="$($user.sAMAccountName)#RES.GROUP"}
}
here I want to replace AD attribute "userPrincipalName" with the value of sAMAccountName from csv file, something like sAMAccountName#RES.GROUP
this script does not work, can anyone please correct it?
Ok, since your comment shows the CSV file indeed does not have a header, I would suggest changing the code to:
$data = Import-Csv -Path .\group.csv -Header 'sAMAccountName'
foreach($user in $data) {
$adUser = Get-ADUser -Filter "SamAccountName -eq '$($user.sAMAccountName)'" -ErrorAction SilentlyContinue
if ($adUser) {
$newUPN = '{0}#res.group' -f $user.sAMAccountName
$adUser | Set-ADUser -UserPrincipalName $newUPN
}
else {
Write-Warning "No user with SamAccountName '$($user.sAMAccountName)' could be found.."
}
}
This way, any mistakes in the file will not make the code quit when a user with that samaccountname cannot be found. Instead, in that case you will see a warning about it and the code will continue with the rest of the data.
It might be worth mentioning that you can use parameter -Server on both the Get-ADUser and Set-ADUser cmdlets to make sure you use the same domain server (DC) to set the new UPN. Otherwise, you can set it on one DC, but are looking at another which doesn't show the change immediately because the servers need time to synchronize..
Now that we have cleared up the question about the CSV and to answer your comment:
If you want to do this as a two-script solution, here's how you can do that
step 1: get all users in the search OU that have a UserPrincipalName ending in '*#test.group'
$searchBase = "OU=Teams,OU=Prod,DC=RES,DC=TEST,DC=GROUP"
Get-ADUser -SearchBase $searchBase -Filter "UserPrincipalName -like '*#test.group'" |
# select ony the SamAccountName and write to CSV with column header
Select-Object SamAccountName | Export-Csv -Path .\group.csv -NoTypeInformation
step 2: read the csv created above and
$searchBase = "OU=Teams,OU=Prod,DC=RES,DC=TEST,DC=GROUP"
$data = Import-Csv -Path .\group.csv
$result = foreach($user in $data) {
$adUser = Get-ADUser -SearchBase $searchBase -Filter "SamAccountName -eq '$($user.sAMAccountName)'" -ErrorAction SilentlyContinue
# if we have a user object AND its UserPrincipalName is not as desired go ahead and change that
if ($adUser) {
if ($adUser.UserPrincipalName -notlike '*#res.test.group') {
$newUPN = '{0}#res.test.group' -f $user.sAMAccountName
$adUser | Set-ADUser -UserPrincipalName $newUPN
# output this user object to be collected in variable $result
$adUser
}
else {
Write-Host "User $($user.sAMAccountName) already has UPN '$($adUser.UserPrincipalName)'"
}
}
else {
Write-Warning "User with SamAccountName '$($user.sAMAccountName)' not found.."
}
}
# now that we have changed some users, create a second csv with all users that were actually changed
if (#($result).Count) {
$result | Select-Object SamAccountName | Export-Csv -Path .\Updatedgroup.csv -NoTypeInformation
}
else {
Write-Host 'No users needed updating'
}
It seems a waste writing only the users SamAccountName property to the csv files.. Especially since Get-ADUser by default already returns these properties: DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID, Surname, UserPrincipalName

Powershell Active Directory Scripting - Bulk disable with change of display name

I am looking for assistance in creating/completing a Powershell script that grabs a user's samAccountName from a .csv file, disables that user in a specific domain, e.g. "foo.bar", and then prepends their AD display name with a single character. This is a bulk disable script, and it has to add that single character to the front/beginning of their display name.
What I have so far is:
Import-Module ActiveDirectory
$Server = read-host "Enter Domain to query/domain controller"
Import-Csv "C:\Temp\samAccountNames.csv" | ForEach-Object {
$samAccountName = $_."samAccountName"
Get-ADUser -Server $Server -Identity $samAccountName | Disable-ADAccount
}
Now, what I need to do is to prepend the display name with the '#' character.
(e.g. "Doe, John" becomes "#Doe, John")
You need to check if the user can be found at all first, then update the displayname and disable the account
Import-Module ActiveDirectory
$characterToPrepend = '#' # the character you want to prepend the DisplayName with
$Server = Read-Host "Enter Domain to query/domain controller"
Import-Csv "C:\Temp\samAccountNames.csv" | ForEach-Object {
$ADUser = Get-ADUser -Server $Server -Filter "SamAccountName -eq '$($_.samAccountName)'" -Properties DisplayName -ErrorAction SilentlyContinue
if ($ADUser) {
# test if the user is not already disabled
if (!$ADUser.Enabled) {
Write-Host "User '$($_.samAccountName)' is already disabled"
}
else {
$newDisplayName = $characterToPrepend + $ADUser.DisplayName
# set the new displayname and disable the user
$ADUser | Set-ADUser -DisplayName $newDisplayName -Enabled $false
}
}
else {
Write-Warning "User '$($_.samAccountName)' does not exist"
}
}
I'm using -Filter to get the user rather than the -Identity parameter because the latter will throw an exception when a user with that SamAccountName could not be found

Disable/Enable AD user account from CSV

How can I enable or disable an AD user account from a csv based on an entry. If the status for both say Active, only one account gets enabled instead of both. Same for the disabled status
CSV file:
Samaccountname,Status
john.doe,Active
jane.doe,Disabled
What I have so far:
Import-CSV -Path c:\folder\adaccounts.csv
ForEach ($User in $Users)
{
IF ($User.Status -contains "Disabled")
{
Get-ADUser -Identity $user.samaccountname | Disable-ADAccount
}
elseif ($User.Status -contains "Active")
{
Get-ADUser -Identity $user.samaccountname | Enable-ADAccount
}
At the top of your script you are importing the CSV but it doesn't look like you have assigned it to a variable for your foreach loop
if you assign it to the $Users variable like below, the rest of the script should then go through your CSV as expected.
$Users = Import-Csv -Path c:\folder\adaccounts.csv
-Contains is an operator to test if something can be found in an array of things, not for testing if a string is equal or not to another string.
I would revise your code like this:
Import-CSV -Path 'c:\folder\adaccounts.csv' | ForEach-Object {
# test if a user with that SamAccountName can be found
$user = Get-ADUser -Filter "SamAccountName -eq '$($_.Samaccountname)'" -ErrorAction SilentlyContinue
if ($user) {
# set Enabled if Status is not 'Disabled'
$user | Set-ADUser -Enabled ($_.Status -ne 'Disabled')
}
else {
Write-Warning "User $($_.Samaccountname) does not exist"
}
}

pull one line at a time from text file to use as a variable in powershell

I am trying to write a PowerShell version 5 script that will query a text document, that simply has a list of usernames, and then run a series of Get-ADUser and Set-ADUser commands against each one.
I have the script working so that if I enter a single username ($SamAccountName is the variable that I use now for the -Identitity modifiers) it works great, but now I want it to run batches from a TXT file.
#Pull a list of users from Text file
$TXTfile = Read-Host -Prompt 'Enter path to Text File'
$file = Get-Content $TXTfile
$file | foreach {
$items = $_.Split("=")
if ($items[0] -eq "") { $SamAccountName = $items[1] }
}
echo $SamAccountName
EDIT: I pulled this code from the web and tried to make it work, but it may be the wrong code, more than likely I'm missing some brackets - what can I say I'm a nube.
The error that I get is:
Enable-ADAccount : Cannot validate argument on parameter 'Identity'. The argument is null. Provide a valid value for the argument, and then try running the command again.
My text file simply looks like this:
SmithA
TurnerH
SchmoJ
TrumpD
Here is the full script that I run for disabling individual accounts:
# this Powershell script will disable a users stored in a TXT file.
# along with disabling their account it will also:
# -Strip thier Group memberships
# -Update some attributes
# -Move the account to the Disabled User's OU
#
#
$UC = Get-Credential
$Date = Get-Date
$Ticket = Read-Host -Prompt 'Input LANDesk ticket number'
#
#
#Prompt for to enter a single username:#
#$samAccountName = Read-Host -Prompt 'Input Username to be disabled:'
#
#
#Pull a list of users from Text file
$TXTfile = Read-Host -Prompt 'Enter path to Text File'
$file = Get-Content $TXTfile
$file | foreach {
$items = $_.Split("=")
if ($items[0] -eq "") { $SamAccountName = $items[1] }
# Enable the account
Enable-ADAccount -Identity $samAccountName
# Remove Group Memberships
(GET-ADUSER –Identity $samAccountName –Properties MemberOf | Select-Object MemberOf).MemberOf | Remove-ADGroupMember -Members $samAccountName
# Update Attributes
#Remove from main dynamic distribution list
Set-ADUser -Identity $samAccountName -company X1
#Clear GAL field "Mail Box Type"
Set-ADUser -Identity $samAccountName -Clear "extensionAttribute1"
#Remove from team dynamic distribution list
Set-ADUser -Identity $samAccountName -Department x2
#Modify Description field with disable date and ticket number
Set-ADUser -Identity $samAccountName -Description "disabled $Date Ticket $Ticket"
# Move Account
Get-ADUser -Identity $samAccountName | move-adobject -targetpath "ou=disabled,ou=users,ou=division,dc=department,dc=company,dc=lcl"
# Disable Account
Disable-ADAccount -Identity $samAccountName
}
Many problems here, you're splitting unnecessarily, not assigning $samAccountName unless the first part is empty which it never will be and you're not doing the work in the loop so at best it would only process the last line.
This should work, although not tested.
# This Powershell script will disable a users stored in a TXT file.
# Along with disabling their account it will also:
# -Strip their group membership
# -Update some attributes
# -Move the account to the Disabled User's OU
$UC = Get-Credential
$Date = Get-Date
$Ticket = Read-Host -Prompt 'Input LANDesk ticket number'
#Pull a list of users from Text file
$TXTfile = Read-Host -Prompt 'Enter path to Text File'
$samAccountNames = Get-Content $TXTfile
foreach ($samAccountName in $samAccountNames)
{
# Enable the account
Enable-ADAccount -Identity $samAccountName
# Remove Group Memberships
Get-ADUser –Identity $samAccountName –Properties MemberOf | Select-Object -ExpandProperty MemberOf | Remove-ADGroupMember -Members $samAccountName
# Update Attributes
#Remove from main dynamic distribution list
Set-ADUser -Identity $samAccountName -company X1
#Clear GAL field "Mail Box Type"
Set-ADUser -Identity $samAccountName -Clear "extensionAttribute1"
#Remove from team dynamic distribution list
Set-ADUser -Identity $samAccountName -Department x2
#Modify Description field with disable date and ticket number
Set-ADUser -Identity $samAccountName -Description "disabled $Date Ticket $Ticket"
# Move Account
Get-ADUser -Identity $samAccountName | move-adobject -targetpath "ou=disabled,ou=users,ou=division,dc=department,dc=company,dc=lcl"
# Disable Account
Disable-ADAccount -Identity $samAccountName
}