PowerShell - Disable and move users

Hi EE

This is something that has been bothering me lately on a too many step process that I think can be done with PS ..

I need help with taking a list of users and Disabling them and moving them to a specific OU ... but .. there is more to it .. see below.

I currently do this with a VB script and PS

Need to:
*Disable the accounts on the txt file ( I currently use a VB Script )
*Move them to MyDomain/Disabled Accounts/ ( Same VB Script as above )
*Add a Note to the Office field: Disabled <Date> and by who ( In the new script , I can enter this each day to the file or have it prompt me ?
*Remove all the groups assosiated with the accounts and save a txt file for each ( I currently use PS for this )
* I also need an output file that shows:
*** If the script disabled the account or if the account was already disabled
*** The DN of the account prior to the move to Disabled Accounts OU
*** If the account was moved or the SamAccount was invalid

This is ALOT to ask for .. maybe we can take it in steps ?
LVL 2
MilesLoganAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kent DyerIT Security Analyst SeniorCommented:
Did you see this?

http://gallery.technet.microsoft.com/scriptcenter/PowerShell-to-Disable-c55a8862

It should be very easy to "pipe" the before and after.

HTH,

Kent
0
SubsunCommented:
I have modified this code which I created for another question.. try this and see if it works for you..

Import-Module ActiveDirectory

Function De-Provision {
    [CmdletBinding()]
    param(  
	[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)]
        [String]$SAMAccountName
    ) 
 
    process {
		$user = Get-ADUser $SAMAccountName -properties memberof,Enabled
		Echo "Working on User $($user.SAMAccountName)"
		Echo "$($user.distinguishedName)"
		#Disable User
			If ($user.Enabled -eq $true) 
			{
				$user | Disable-ADAccount
				Echo "$($user.SAMAccountName) is disabled by script"
			}
				Elseif ($user.Enabled -eq $False) {
				Echo "$($user.SAMAccountName) is already disabled"
			}
			#Remove Group membership
			Try{
				$Groups = Get-ADPrincipalGroupMembership $user
				Echo "Group membership $($user.SAMAccountName)"
				$Groups | Select -ExpandProperty Name
				$Groups | ?{$_.Name -ne "Domain Users"} |%{Remove-ADPrincipalGroupMembership $user -MemberOf $_ -Confirm:$False}
				Echo "Removed group membership for $($user.SAMAccountName)"
			}
			Catch{
				Echo "Error in group membership removal for $($user.SAMAccountName) : $($_.Exception.Message)"
			}
		        #Move user object
			Try{
				$user | Move-ADObject -TargetPath "OU=Disabled Accounts,DC=Domain,DC=Com" -EA STOP
				Echo "Moved user $($user.SAMAccountName) to Disabled Accounts OU"
			}
			Catch{
				Echo "Error in moving user $($user.SAMAccountName) : $($_.Exception.Message)"
			}
		}
}

GC User.txt | De-Provision >>C:\temp\De-ProvisionReport.txt

Open in new window

0
MilesLoganAuthor Commented:
Hi Subsun .. I got this to disable some accunts .. any way you can add this to the script ?

Foreach ($user in Get-Content "e:\Projects\Term\TermUsers.txt") {
    $report = "e:\Projects\Term\groups_$((Get-ADUser $user -properties SamAccountName).SamAccountName)_$(Get-date -f dd-MM-yyyy).txt"
    "=============== UserName $user ===============" >> $report
    $Groups = (Get-ADUser $user -Properties memberof).memberof
    $Groups | Get-ADGroup | Select -ExpandProperty Name >> $report
    $Groups | Get-ADGroup | Remove-ADGroupMember -member $user -Confirm:$False
}

This will remove the groups from each account and save a text file .
What about and output of the changes to the accounts ? I need it to show below ..

SamAccountID , If it was moved, if it was already disabled, Account DN prior to the move
0
Webinar: What were the top threats in Q2 2018?

Every quarter, the WatchGuard Threat Lab releases an Internet Security Report that describes and analyzes the top threat trends impacting companies around the world. Are you ready to learn more about the top threats of Q2 2018? Register for our Sept. 26th webinar to learn more!

SubsunCommented:
Try..
Import-Module ActiveDirectory

Function De-Provision {
    [CmdletBinding()]
    param(  
	[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)]
        [String]$SAMAccountName
    ) 
 		process {
		$user = Get-ADUser $SAMAccountName -properties memberof,Enabled
		$report = "e:\Projects\Term\groups_$($user.SAMAccountName)_$(Get-date -f dd-MM-yyyy).txt"
		"=============== UserName $($user.SAMAccountName)===============" >> $report
		"$($user.distinguishedName)" >> $report
		#Disable User
			If ($user.Enabled -eq $true) 
			{
				$user | Disable-ADAccount
				"$($user.SAMAccountName) is disabled by script" >> $report
			}
				Elseif ($user.Enabled -eq $False) {
				"$($user.SAMAccountName) is already disabled" >> $report
			}
			#Remove Group membership
			Try{
				$Groups = Get-ADPrincipalGroupMembership $user
				"Group membership $($user.SAMAccountName)" >> $report
				$Groups | Select -ExpandProperty Name >> $report
				$Groups | ?{$_.Name -ne "Domain Users"} |%{Remove-ADPrincipalGroupMembership $user -MemberOf $_ -Confirm:$False}
				"Removed group membership for $($user.SAMAccountName)" >> $report
			}
			Catch{
				"Error in group membership removal for $($user.SAMAccountName) : $($_.Exception.Message)" >> $report
			}
		        #Move user object
			Try{
				$user | Move-ADObject -TargetPath "OU=Disabled Accounts,DC=Domain,DC=Com" -EA STOP
				"Moved user $($user.SAMAccountName) to Disabled Accounts OU" >> $report
			}
			Catch{
				"Error in moving user $($user.SAMAccountName) : $($_.Exception.Message)" >> $report
			}
		}
}

GC User.txt | De-Provision

Open in new window

0
MilesLoganAuthor Commented:
HI Subsun .. I tried the new code but it did not output the groups file.  

It did disable the accounts, moved them to the new OU and removed the groups.
0
SubsunCommented:
Line 27 should do it.. All the information is send to same file... I will test it when I get a chance..
0
SubsunCommented:
I can see the group details in log..

=============== UserName subsun===============
CN=Subsun,CN=Users,DC=Max,DC=com
subsun is disabled by script
Group membership subsun
Domain Users
Administrators
Backup Operators
Cryptographic Operators
Certificate Service DCOM Access
Cert Publishers
Account Operators
Allowed RODC Password Replication Group
Denied RODC Password Replication Group
Delegated Setup

Removed group membership for subsun
Moved user subsun to Disabled Accounts OU
0
MilesLoganAuthor Commented:
My mistake , I was not paying attention .. This does work but ... I need two output files.

1. Keep the current output on the text file.
2. CSV file that shows the SamAccountName,if the script Moved the account or it was already in the Disabled Accounts OU,If it was disabled or not already,DN prior to the move.

Last I need to add to each account on the .txt file a note in the Office field ( Disabled by xxxx on <Date> )

Thank you so much !
0
SubsunCommented:
Try this and see if it works as expected..
Import-Module ActiveDirectory

Function De-Provision {
    [CmdletBinding()]
    param(  
	[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)]
        [String]$SAMAccountName,
	[Parameter(Mandatory=$True,ValueFromPipelinebyPropertyName=$True)]
	[String]$Disabledby
    )
 		process {
		$user = Get-ADUser $SAMAccountName -properties memberof,Enabled
		$report = "e:\Projects\Term\groups_$($user.SAMAccountName)_$(Get-date -f dd-MM-yyyy).txt"
		"=============== UserName $($user.SAMAccountName)===============" >> $report
		"$($user.distinguishedName)" >> $report
		#Disable User
			If ($user.Enabled -eq $true) 
			{
				$user | Disable-ADAccount
				"$($user.SAMAccountName) is disabled by script" >> $report
				$Dis = "Disabled by script"
				$user | Set-ADUser -Office "Disabled by $Disabledby $(Get-date)"
			}
				Elseif ($user.Enabled -eq $False) {
				"$($user.SAMAccountName) is already disabled" >> $report
				$Dis = "Already disabled"
			}
			#Remove Group membership
			Try{
				$Groups = Get-ADPrincipalGroupMembership $user
				"Group membership $($user.SAMAccountName)" >> $report
				$Groups | Select -ExpandProperty Name >> $report
				$Groups | ?{$_.Name -ne "Domain Users"} |%{Remove-ADPrincipalGroupMembership $user -MemberOf $_ -Confirm:$False}
				"Removed group membership for $($user.SAMAccountName)" >> $report
			}
			Catch{
				"Error in group membership removal for $($user.SAMAccountName) : $($_.Exception.Message)" >> $report
			}
		        #Move user object
			Try{
				$user | Move-ADObject -TargetPath "OU=Disabled Accounts,DC=Domain,DC=Com" -EA STOP
				"Moved user $($user.SAMAccountName) to Disabled Accounts OU" >> $report
				$Move = "Moved user"
			}
			Catch{
				"Error in moving user $($user.SAMAccountName) : $($_.Exception.Message)" >> $report
				$Move = $_.Exception.Message
			}
		New-Object PSObject -Property @{
		SAMAccountName = $user.SAMAccountName
		MoveStat = $Move
		Disabled = $Dis
		DN = $user.distinguishedName
		} | Export-Csv $($report -replace "\.Txt",".csv") -NTI
		}
}

GC User.txt | De-Provision -Disabledby "Domain\MilesLogan"

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
MilesLoganAuthor Commented:
Hi SUbsun .. thank you for hanging in this with me .. this does output the .csv file with the data that I need  , but can it be one .csv file containing the output for all users ?

all the users that where included in User.txt .. showing the same outout of what was done .
0
SubsunCommented:
Remove  | Export-Csv $($report -replace "\.Txt",".csv") -NTI from line 54 and change last line to..

GC User.txt | De-Provision -Disabledby "Domain\MilesLogan" | Export-csv "E:\Projects\Term\De-Provision_Report_$(Get-date -f dd-MM-yyy-hhmmss).csv" -NTI

Open in new window

0
MilesLoganAuthor Commented:
Works perfect .. one minor change if I could .. the note that is being added to the Office field , I need it on all the accounts . Regardless if the script disabled it or if the account was alread disabled .
0
SubsunCommented:
Move the 22nd line and place it just before  #Remove Group membership..
0
MilesLoganAuthor Commented:
Thank you so much Subsun !! you saved me alot of time on this daily check we do .
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.