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
Related
Giving myself a fun little project today I thought, but now it's grown into an issue and the solution eludes me. I have a massive .Csv file with all our employees sAMAccountName and telephoneNumber attributes. I would like to update all of the telephone numbers in our active directory. I was poking around some of my old scripts, taking parts and pieces that would work for this my first iteration got me too here.
$Users = Import-Csv -Path C:\Results\EmployeeExtsTest.csv
ForEach ($User in $Users) {
$User = $User.sAMAccountName
$telephoneNumber = $User.telephoneNumber
Get-ADUser -Identity $User | Set-ADUser -telephoneNumber $telephoneNumber
}
That's when I discovered that PowerShell doesn't have a -telephoneNumber attribute. So I did some digging and then arrived here.
$Users = Import-Csv -Path C:\Results\EmployeeExtsTest.csv
ForEach ($User in $Users) {
$User = $User.sAMAccountName
$telephoneNumber = $User.telephoneNumber
Get-ADUser -Identity $User | Set-ADUser -Add #{telephoneNumber=$telephoneNumber}
}
I tested it out with my user at first and I keep getting the following.
Set-ADUser : Cannot validate argument on parameter 'Add'. The argument is null or an element of the argument collection contains a null value.
At line:6 char:50
+ ... -Identity $User | Set-ADUser -Add #{telephoneNumber=$telephoneNumber}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Set-ADUser], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.SetADUser
I know that it's reading my .Csv correctly because I can call it just fine. It outputs the following.
sAMAccountName telephoneNumber
-------------- ---------------
zgroven 1121
I know this solution "should" be easy but it's completely escaping me!
To expand on #PaulWain answer. Active Directory Users and Computers displays Telephone Number, the AD Attribute is telephoneNumber, but Set-ADUser oddly uses the parameter OfficePhone for setting it. Another quirk due to OfficePhone being a "special" field, when clearing with Set-ADUser you actually have to use telephoneNumber as the field. e.g.:
$Users = Import-Csv -Path C:\Results\EmployeeExtsTest.csv
ForEach ($UserEntry in $Users) {
$User = Get-ADUser -Filter "samAccountName -like '$($UserEntry.sAMAccountName)'" -Properties *
#Check to see if the user exists
if($User)
{
#Check to see if the Office Phone number has been cleared in CSV
if ([string]::IsNullOrEmpty($UserEntry.telephoneNumber))
{
#Clear the user's OfficePhone (telephoneNumber) in Active Directory
Set-ADUser -Identity $User -Clear telephoneNumber
}
else
{
#Update the user in Active Directory
Set-ADUser -Identity $User -OfficePhone $UserEntry.telephoneNumber
}
}
else
{
Write-Host "User $($UserEntry.sAMAccountName) does not exist in Active Directory"
}
}
One thing I add to my script is to use the -Filter parameter on my Get-ADUser that way I can verify the user exists without Get-ADUser throwing an error. See my answer for more information "Determine If Users Are In Active Directory With PowerShell":
The other method is to modify all of the properties all at once, and then use the Set-ADUser -Instance parameter to set them all at once (note: OfficePhone/telephoneNumber are special and have to be cleared manually like the above code, other fields can be manually cleared/set blank):
$Users = Import-Csv -Path C:\Results\EmployeeExtsTest.csv
ForEach ($UserEntry in $Users) {
$User = Get-ADUser -Filter "samAccountName -like '$($UserEntry.sAMAccountName)'" -Properties *
#Check to see if the user exists
if($User)
{
#Check to see if the Office Phone number has been cleared in CSV
if ([string]::IsNullOrEmpty($UserEntry.telephoneNumber))
{
#Clear the user's OfficePhone (telephoneNumber) in Active Directory
Set-ADUser -Identity $User -Clear telephoneNumber
}
else
{
#Modify Local instance of the user's properties
$User.OfficePhone = $UserEntry.telephoneNumber
}
#Modify Local instance of other user's properties
$User.GivenName = $UserEntry.GivenName
$User.Surname = $UserEntry.Surname
#..... etc.....
#Update the user in Active Directory
Set-ADUser -Instance $User
}
else
{
Write-Host "User $($UserEntry.sAMAccountName) does not exist in Active Directory"
}
}
I believe that you are being misled by what is displayed and what the actual name of the property is, due to behind-the-scenes aliasing.
Try using this instead:
set-aduser $user -OfficePhone $telephoneNumber
The final script that got me through this is here
$Users = Import-Csv -Path C:\Results\EmployeeExts.csv
ForEach ($U in $Users) {
$User = $U.sAMAccountName
$telephoneNumber = $U.telephoneNumber
Set-ADUser $User -OfficePhone $telephoneNumber
}
Because I work for a school district I will be adding on more to this in the future to look for employees that are missing. As it stands now this script just updated nearly 1000 AD accounts perfectly (aside from the missing employees that have left). I want to thank all of you for helping in giving me pieces of this answer. You've made me better at my job.
Special thanks to #PaulWain and #HAL9256
Basically the idea of this script is to create a new user in AD but to also copy groups from another user in AD from a search with user input.
For example copy sales groups from a current team member to the newly created member. The error I'm getting is that my $ID variable is always empty and -Identity cant use it. If I hardcode the user I want to copy from this code works.
I can just ask for user input and have them put in the identity / username / samaccountname to copy groups from but they're not going to know that off the top of their head as the naming convention in AD includes employee numbers. They'd have to navigate AD to find that and this avoids the point of the script.
I want this script to be able to lookup a user based on just name for ease of use. This is why it uses -filter. If you have suggestions on how to handle potential duplicates of users with same name during this search I'm all ears for that too.
After it finds the user to copy from it copies the groups from the searched user to the newly created user.
Thanks for any help!
Do {
$Given = Read-Host -Prompt "Input new user first name"
$Surname = Read-Host -Prompt "Input new user last name"
$PW = Read-Host -Prompt "Input new user password"
$Phone = Read-Host -Prompt "Input new user phone number"
$NewSam = Read-Host -Prompt "Input preferred new user ID"
$User = "$Given $Surname"
$Confirmation = Read-Host "You input '$User' , '$NewSam' , '$PW' , and '$Phone' is this correct (y/n)?"
}
while ($confirmation -ne "y")
New-ADUser -Name $User -GivenName $Given -Surname $Surname -SamAccountName $NewSam -AccountPassword (ConvertTo-SecureString -AsPlaintext "$PW" -Force) -Enabled $True `
-OfficePhone $Phone -ChangePasswordAtLogon $true
Do {
$clone = Read-Host -Prompt "Who are we copying groups from?"
$Confirmation2 = Read-Host "You input '$clone' is this correct (y/n)?"
}
while ($confirmation2 -ne "y")
$ID = Get-ADUser -Filter 'Name -eq "$clone"'| Select-Object -ExpandProperty SamAccountName
$GetUserGroups = Get-ADUser -Identity "$ID" -Properties memberof | Select-Object -ExpandProperty memberof
$GetUserGroups | Add-ADGroupMember -Members $NewSam -Verbose
While asking for user input via Read-Host is always tricky (a user can type in any bogus text he/she wants), I would at least give that user the opportunity to quit the loop by adding the q option in there as well.
Then you really should first do a check if the user perhaps already exists or not before creating with New-ADUser.
Finally, $GetUserGroups | Add-ADGroupMember -Members $NewSam -Verbose will not work as you expect, because the -Identity parameter for Add-ADGroup only takes one single group id at a time, so you need to loop over the groups there.
Try
do {
$Given = Read-Host -Prompt "Input new user first name"
$Surname = Read-Host -Prompt "Input new user last name"
$PW = Read-Host -Prompt "Input new user password"
$Phone = Read-Host -Prompt "Input new user phone number"
$NewSam = Read-Host -Prompt "Input preferred new user ID (SamAccountName)"
$User = "$Given $Surname"
$Confirmation = Read-Host "You input '$User' , '$NewSam' , '$PW' , and '$Phone' is this correct (y/n/q)?"
switch -Wildcard ($confirmation) {
'q*' {
# user wants to quit
exit
}
'y*' {
# here first check if that user already exists or not
$existingUser = Get-ADUser -Filter "SamAccountName -eq '$NewSam'"
if ($existingUser) {
Write-Warning "A user with SamAccountName '$NewSam' already exists"
$Confirmation = 'n' # rerun the loop
}
}
}
} while ($confirmation -notlike "y*")
# now proceed creating the new AD user
# because New-ADUser can take a lot of parameters, the cvleanest way is to use splatting
$userProps = #{
Name = $User
GivenName = $Given
Surname = $Surname
SamAccountName = $NewSam
AccountPassword = ConvertTo-SecureString -AsPlaintext $PW -Force
Enabled = $True
OfficePhone = $Phone
ChangePasswordAtLogon = $true
# add switch parameter PassThru, so the cmdlet returns the new user object
PassThru = $true
}
$newUser = New-ADUser #userProps
do {
$clone = Read-Host -Prompt "Who are we copying groups from? (SamAccountName)"
$Confirmation = Read-Host "You input '$clone' is this correct (y/n/q)?"
switch -Wildcard ($Confirmation) {
'q*' {
# user wants to quit
Write-Host "New user '$($newUser.Name)' has been created but not added to any groups.."
exit
}
'y*' {
# here first check if that user already exists or not
$cloneUser = Get-ADUser -Filter "SamAccountName -eq '$clone'" -Properties MemberOf
if (!$cloneUser) {
Write-Warning "A user with SamAccountName '$clone' does not exist"
$Confirmation = 'n' # rerun the loop
}
else {
# get the MemberOf properties from the second user
# and add the new user to these groups
$cloneUser.MemberOf | ForEach-Object {
$_ | Add-ADGroupMember -Members $newUser -Verbose
}
}
}
}
}
while ($confirmation -notlike "y*")
P.S. I'm using wildcard comparisons ('y*') on the confirmation input because otherwise if a user types 'yes' the loop will not see that as a YES
Your script starts to go sideways here:
$ID = Get-ADUser -Filter 'Name -eq "$clone"'| Select-Object -ExpandProperty SamAccountName
$GetUserGroups = Get-ADUser -Identity "$ID" -Properties memberof | Select-Object -ExpandProperty memberof
And you're so close, what's needed is:
$ID = Get-ADUser -Filter "Name -eq '$clone'"|
Select-Object -ExpandProperty SamAccountName
The Filter requires single quotes around the name. The documentation on this is horrible and, for the Filter parameter, uses ScriptBlocks (code inside curly braces) in the examples while the actual type is [string]. I learned to stick with strings after fixing problems that were obscured by using ScriptBlocks.
You wouldn't even run into this problem if you simplified to:
$ID = Get-ADUser -Identity $clone |
Select-Object -ExpandProperty SamAccountName
As long as we're simplifying, you only need one line:
$GetUserGroups = Get-ADUser -Identity $clone -Properties memberof |
Select-Object -ExpandProperty memberof
One more thing to consider. While piping to Select-Object is the PowerShell way and is the style I tend to use from the command line, in scripts I personally prefer:
$GetUserGroups = (Get-ADUser -Identity $clone -Properties memberof).memberof
But this is a matter of taste (while also being faster (which only matters in long running scripts)).
I'm trying to import manager attribute to active directory for set of users using the following CSV file template
GivenName Surname DisplayName Department Title mail MobilePhone Manager SamAccountName
John Smith John Smith IT IT Manager john#example.com 1234 Mark Ebert JohnS
I used the below script and but it throws out an error.What i'm thinking it is due to manager attribute required to be in distinguished name format and **but i cannot change the csv manager column name as it comes from a different program.**The manager name in the CSV file shows in first name and last name format. What i need is to import the data on it to AD like the way it is.Any alternative methods available for this scenario.Here is the example script i used.
# Import AD Module
Import-Module ActiveDirectory strong text
$users = Import-Csv -Path C:\temp\MergedTo_AD.csv
foreach ($user in $users)
{Get-ADUser -Filter "SamAccountName -eq '$($user.samaccountname)'" | Set-ADUser -GivenName $($User.GivenName) -Surname $($User.Surname) -DisplayName $($User.DisplayName) -title $($User.title) -EmailAddress $($User.EmailAddress) -MobilePhone $($User.MobilePhone) $User -manager $ID }
If your CSV looks like this:
GivenName,Surname,DisplayName,Department,Title,mail,MobilePhone,Manager,SamAccountName
John,Smith,John Smith,IT,IT Manager,john#example.com,1234,Mark Ebert,JohnS
Joe,Bloggs,Joe Bloggs,Marketing,Administrative Assistant,joe#example.com,87954,,JoeB
Then you can see that in the second example the Manager property is empty.
To best deal with columns that could be empty, use Splatting for properties that are present in the CSV, while omitting empty fields:
Something like this:
$users = Import-Csv -Path C:\temp\MergedTo_AD.csv
foreach ($user in $users) {
# first try and find the user object in AD
$adUser = Get-ADUser -Filter "SamAccountName -eq '$($user.SamAccountName)'" -Properties Manager -ErrorAction SilentlyContinue
if ($adUser) {
# we have a valid user. create a splatting Hashtable to use with Set-ADUser
# Leave out the Manager for now, as we first need to make sure we can actually find a DN for this property.
$userProps = #{
# take out any properties you do not want to (re) set
GivenName = $user.GivenName
Surname = $user.Surname
DisplayName = $user.DisplayName
Title = $user.Title
EmailAddress = $user.mail
MobilePhone = $user.MobilePhone
}
# try and get the manager object from the $user.Manager column which may or may not have been set
if (![string]::IsNullOrWhiteSpace($user.Manager)) {
# try and find an AD user with the given DisplayName. You could also try with the `Name` property
$manager = Get-ADUser -Filter "DisplayName -eq '$($user.Manager)'" -ErrorAction SilentlyContinue
if ($manager) {
# add the 'Manager' entry to the Hashtable for properties to set
$userProps['Manager'] = $manager.DistinguishedName
}
else {
Write-Warning "Could not find '$($user.Manager)' in AD.."
}
}
else {
Write-Warning "Manager column for user '$($user.SamAccountName)' is empty.."
}
# here we set the properties to the user according to the CSV file
Write-Host "Updating user properties for '$($user.SamAccountName)'"
$adUser | Set-ADUser #userProps
}
else {
Write-Warning "User '$($user.SamAccountName)' could not be found.."
}
}
I'm not a scripting expert at all.I amended the script as below as per your suggestion.
# Import AD Module
Import-Module ActiveDirectory
$users = Import-Csv -Path C:\temp\MergedTo_AD.csv
{Get-ADUser -Filter "SamAccountName -eq '$($user.samaccountname)'" $FirstName,$LastName = (-split $User.Manager).Trim() $ID = (Get-ADUser -LDAPFilter "(&(GivenName=*$FirstName*)(SurName=*$LastName*))").SamAccountName (Get-ADUser -LDAPFilter "(&(GivenName=*$FirstName*)(SurName=*$LastName*))").SamAccountName| Set-ADUser -GivenName $($User.GivenName) -Surname $($User.Surname) -DisplayName $($User.DisplayName) -title $($User.title) -EmailAddress $($User.EmailAddress) -OfficePhone $($User.OfficePhone) -MobilePhone $($User.MobilePhone) -manager $($User.manager) }
I'm getting below error
Get-ADUser : The search filter cannot be recognized
At C:\Temp\PowershellScript-Users Import.ps1:5 char:128
+ ... im() $ID = (Get-ADUser -LDAPFilter "(&(GivenName=*$FirstName*)(SurNam ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8254,Microsoft.ActiveDirectory.Management.Commands.GetADUser
I've reviewed the code and the reason it fails is because you cannot add the manager using the variable '$ID' is that it has no reference, nor does it resolve to the managers active directory user account. Your choices are either add the managers Distinguished Name to your csv file or stick it in your code to resolve the managers Distinguished Name.
#Import CSV File to set variable for the user’s logon name of whom manager’s field needs to be filled + delimiter
$users = Import-Csv -Delimiter ";" -Path "C:\temp\MergedTo_AD.csv"
foreach ($user in $users) {
#The Managers AD Sam Account Name
$ManagersaMACCount = "saMACcount"
#The Managers AD Distinguished Name
$ManagerID = (Get-ADUser -identity $ManagersaMACCount).DistinguishedName
#Example of Setting User's Manager Attribute -Example below
#Get-aduser -identity $user | Set-ADUser -Manager $ManagerID
#Using your code to filter AD Sam Accounts Based on column samaccountname in the csv file
Get-ADUser -Filter "SamAccountName -eq '$($user.samaccountname)'" `
#Pipe Set Users GivenName Based on column GivenName
| Set-ADUser -GivenName $($User.GivenName) `
#Set Users Surname Based on column Surname
-Surname $($User.Surname) `
#Set Users Display Name Based on column DisplayName
-DisplayName $($User.DisplayName) `
#Set Users Title Based on column Title
-title $($User.title) `
#Set Users Email Address Based on column EmailAddress
-EmailAddress $($User.EmailAddress) `
#Set Users Mobile Phone Based on column MobilePhone
-MobilePhone $($User.MobilePhone) `
#Set Users Manager Based on the Distinguished Name Attribute In Active Directory
-manager $ManagerID
}
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
}
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}