[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

powershell script to delete AD accounts

Posted on 2014-07-10
38
Medium Priority
?
714 Views
Last Modified: 2014-08-20
Hi,
I need a powershell script to delete user's AD accounts and their home drives in files servers.

Oue enviroment is EMEA based and users' home drives are on their local file servers.
Script should see the .txt file to see left user's user IDs and then see the .txt file for the list of file servers and delete their home drives.
Can you please help me with this below code?

$leftUsers = Get-Content "c:\temp\testadusers.txt"
$UsersPath = Get-content "c:\temp\serverlist.txt"
$dumpPath = "c:\temp\deleteMe"
$logfile = "TidyUsers-$(Get-date -format ddMMyy).log"

if($(Test-path $dumpPath) -ne $True){mkdir $dumppath -force}

$log = @()

foreach($user in $leftUsers) {
foreach ($CurrentServer in $Userpath) {
$CurrentPath = Join-Path -Path "\\$CurrentServer" -ChildPath "$User"
write-verbose -Message "Searching the accounts in servers."
If(Test-path $CurrentPath) {
$log += "Moving $CurrentPath to $dumpPath"
move-Item $CurrentPath -destination $dumpPath -whatif
 } else {
$log += "$CurrentPath not found"

 }
 }
}

$log += ""
$log += "$(GCI $dumpPath)"
$log >.\$LogFile
0
Comment
Question by:kuzum
  • 22
  • 12
  • 3
  • +1
38 Comments
 
LVL 25

Expert Comment

by:Coralon
ID: 40191730
Seems like kind of a difficult way to do this.. Are they really home directories?

import-module -name ActiveDirectory -erroraction silentlycontinue
$Users = get-content -path <path>\userlist.txt

$Users | foreach-object {
     $CurrentUser = Get-ADUser -identity $_ -properties homeDirectory
     remove-item -path $($CurrentUser).homedirectory -force -recurse
     $CurrentUser | remove-aduser
}

Open in new window


You can insert logging code in it, or just turn on a transcript as part of the script.. A lot more can be done, but this is the basics of what you are describing?  Mulitple files can be done, but it's definitely longer..

Coralon
0
 
LVL 17

Expert Comment

by:Premkumar Yogeswaran
ID: 40193676
Try the below script
Input of user should be logon name

Import-Module ActiveDirectory

$users = Get-Content users.txt

foreach ($user in $users) {

    $aduser = Get-ADUser $user -Properties HomeDirectory

    Remove-Item $aduser.HomeDirectory
    Remove-ADUser $aduser.samAccountName -Confirm:$False

}

Open in new window


Refer:
http://www.experts-exchange.com/OS/Microsoft_Operating_Systems/Q_27680111.html
0
 

Author Comment

by:kuzum
ID: 40195943
thank you for responses,

Can you please amend the both script abouve to take ownership of home folders first and then to delete home folders after as I am receving permission error such as

remove-Item : Cannot remove item \\servername \username$\Conventional bond prospectus\Thumbs.db: Not Enough permission to perform operation.
At line:7 char:16
+     Remove-Item <<<<  $aduser.HomeDirectory
    + CategoryInfo          : PermissionDenied: (Thumbs.db:FileInfo) [Remove-Item], IOException
    + FullyQualifiedErrorId : RemoveFileSystemItemUnAuthorizedAccess,Microsoft.PowerShell.Commands.RemoveItemCommand

remove-Item : Cannot remove item \\servername\username$\XXX backup\Favorites\Links\desktop.ini: Not Enough permission to perform operation.
At line:7 char:16
Home folders are also containts users desktop and systemfiles etc via  group policy ( folder redirection)
0
Creating Active Directory Users from a Text File

If your organization has a need to mass-create AD user accounts, watch this video to see how its done without the need for scripting or other unnecessary complexities.

 
LVL 25

Expert Comment

by:Coralon
ID: 40195982
The 2 scripts are basically identical above..

But,

import-module -name ActiveDirectory -erroraction silentlycontinue
$Users = get-content -path <path>\userlist.txt

$Users | foreach-object {
	$CurrentUser = Get-ADUser -identity $_ -properties homeDirectory
	$CurrentHomeDirectory = $($CurrentUser).homedirectory 
	
	takeown.exe /f "$CurrentHomeDirectory" /a /r /d y /skipsl 
	cacls.exe "$CurrentHomeDirectory" /e /t /g administrators:f

	remove-item -path $CurrentHomeDirectory -force -recurse
	$CurrentUser | remove-aduser
}

Open in new window


The key here is the takeown.exe which comes with 2008R2, Windows 7, etc. That set of command line switches will:
/f - specify the directory
/a - assign the Administrators group ownership
/r - Recurse the directory
/d y - answers the prompts from /r with a Yes to force the ownership change
/skipsl - skip any symbolic links.. this should prevent it from being caught in a loop.

After the ownership changes, cacls.exe adds an Administrators:Full permission to everything.

Coralon
0
 

Author Comment

by:kuzum
ID: 40196292
thanks Coralon,

Still having smiliar small issues with permissions, May be best to change it from administrators to currently logged in user?
remove-item <<<<  -path $CurrentHomeDirectory -force -recurse
    + CategoryInfo          : PermissionDenied: (\\server\username$:String) [Remove-Item], UnauthorizedAccessException
    + FullyQualifiedErrorId : RemoveItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.RemoveItemCommand
0
 

Author Comment

by:kuzum
ID: 40196299
sorry forgot to add this part of the error

takeown.exe : ERROR: Invalid argument/option - '/skipsl'.
At line:8 char:13
+     takeown.exe <<<<  /f "$CurrentHomeDirectory" /a /r /d y /skipsl
    + CategoryInfo          : NotSpecified: (ERROR: Invalid ...on - '/skipsl'.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
 
Type "TAKEOWN /?" for usage.

cacls.exe : The network name cannot be found.
At line:9 char:11
+     cacls.exe <<<<  "$CurrentHomeDirectory" /e /t /g administrators:f
    + CategoryInfo          : NotSpecified: (The network name cannot
0
 
LVL 25

Expert Comment

by:Coralon
ID: 40198428
I forgot to add that you do need to run it from an elevated powershell prompt.

The takeown is going to require administrator permissions on the target device, as will the cacls.exe
But, if skipsl is giving you problems, just leave that switch off.  I'm running takeown.exe on my Win8.1 box, so the Win2k8R2 version may not have it.

Each of those commands needs to run successfully in a row.  Try it by hand from an elevated powershell prompt, and check your success with it.

Coralon
0
 

Author Comment

by:kuzum
ID: 40198432
I'm running it from windows 7 machine with my admin account that also has access to server. (2003 file server, 2008 AD servers)

Did I get your answer correct?
0
 
LVL 25

Expert Comment

by:Coralon
ID: 40198434
Yes.. but on your Windows 7 machine, is the powershell prompt elevated, or is UAC turned off?

Coralon
0
 

Author Comment

by:kuzum
ID: 40198532
Yes UAC is on and I do get credentials window promted to enter admin account details when I am doing admin related work on my local machine hence I am running Powershel ISE with my admin account which is same account I use on servers,
0
 

Author Comment

by:kuzum
ID: 40201260
any suggestion please?
0
 

Author Comment

by:kuzum
ID: 40203493
may be VB script is better idea for this task?
0
 
LVL 25

Expert Comment

by:Coralon
ID: 40205846
Conceptually, your vbscript would be the same mechanics, and we're using utilities on the local system, so it's not really going to be any different.  

You did try it without the /skipsl right?  
The cacls.exe error is interesting.. You'll want to verify if that home directory does in fact really exist.  If it doesn't, you'll need to add more error checking to all of this.

Maybe more like this:

import-module -name ActiveDirectory -erroraction silentlycontinue
$Users = get-content -path <path>\userlist.txt

$Users | foreach-object {
	$CurrentUser = Get-ADUser -identity $_ -properties homeDirectory
	$CurrentHomeDirectory = $($CurrentUser).homedirectory 

	if ((test-path -path $currenthomedirectory) -and ($currenthomedirectory -ne $null)) {
	
		takeown.exe /f "$CurrentHomeDirectory" /a /r /d y /skipsl 
		cacls.exe "$CurrentHomeDirectory" /e /t /g administrators:f
	
		remove-item -path $CurrentHomeDirectory -force -recurse
		$CurrentUser | remove-aduser
	} else {
		write-output $currentuser | select-object -property samaccountname,homeDirectory
	}

Open in new window

0
 

Author Comment

by:kuzum
ID: 40250115
Hi,

I noticed some of the acocunts do not have  holme directory. What should I do in this case?
0
 
LVL 25

Expert Comment

by:Coralon
ID: 40250153
It should work exactly as posted..

If you notice this line:
if ((test-path -path $currenthomedirectory) -and ($currenthomedirectory -ne $null))

The test-path verifies that the directory actually exists.  If the user does not have a home directory, this test will fail, and that part will be skipped.  

(and I have verified that Win2k8R2 does have takeown.exe and it works the same.)

Coralon
0
 

Author Comment

by:kuzum
ID: 40250258
my AD servers are 2008 and file servers ( home drives) are 2003. Can this still work?
thanks
0
 
LVL 25

Expert Comment

by:Coralon
ID: 40251004
Yep.. there is nothing that is OS specific in this script.  The only thing you have to be sure of is that you have takeown.exe on the system you run it from.  I don't believe 2003 had takeown.exe except in the resource kit, so you'd want to run it from your AD server.

Coralon
0
 

Author Comment

by:kuzum
ID: 40251061
thanks Coralon, I am running it from my windows 7 machine. is that ok?
0
 
LVL 25

Expert Comment

by:Coralon
ID: 40251134
As long as you have the RSAT tools for Active Directory installed.

Coralon
0
 

Author Comment

by:kuzum
ID: 40251154
Hi Coralon,

I have updated my Powershell ISE on my windows 7 machine and RSAT tools already installed . What is it that Im doing wrong please?

takeown.exe : ERROR: Invalid argument/option - '/skipsl'.
At line:10 char:3
+         takeown.exe /f "$CurrentHomeDirectory" /a /r /d y /skipsl
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (ERROR: Invalid ...on - '/skipsl'.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
 
Type "TAKEOWN /?" for usage.
cacls.exe : The network name cannot be found.
At line:11 char:3
+         cacls.exe "$CurrentHomeDirectory" /e /t /g administrators:f
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (The network name cannot be found.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
0
 

Author Comment

by:kuzum
ID: 40251371
any ideas? thanks
0
 

Author Comment

by:kuzum
ID: 40251377
--------------------------------------------------------------------------------

I found this on  the net. is this can be because of spaces in the code?
Quote:
takeown /f c:\program files\avg\avg2012\avgsysx.dll
On the command line if a path has any spaces in it, you have to wrap it in double quotes.
For example to run c:\program files\myprog.exe from the command line I have to type
"c:\program files\myprog.exe"

Note the double quotes.
takeown /f "c:\program files\avg\avg2012\avgsysx.dll"
0
 
LVL 25

Assisted Solution

by:Coralon
Coralon earned 2000 total points
ID: 40251395
Definitely.. That's why the script has the double quotes in it.  You'll have to leave out the /skipsl, since that is the first error.  The 2nd one looks like the substitution for $CurrentHomeDirectory isn't happening.  

You may need to add a line above the takeown line to see what it 'sees'

You can add 'write-host "$CurrentHomeDirectory"'  (without the ' marks, but with the " marks), and see if it shows properly.  You should see something like "\\server\share\my directory\filename" if you don't see the " marks, then try changing it to this:
'write-host ([char]34 + $CurrentHomeDirectory + [char]34)' and make sure that comes out correctly.

Coralon
0
 

Author Comment

by:kuzum
ID: 40251401
thanks Coralon
Can you please amend this code as you described for me please?

import-module -name ActiveDirectory -erroraction silentlycontinue
$Users = get-content -path "C:\temp\testadusers.txt"

$Users | foreach-object {
      $CurrentUser = Get-ADUser -identity $_ -properties homeDirectory
      $CurrentHomeDirectory = $($CurrentUser).homedirectory

      if ((test-path -path $currenthomedirectory) -and ($currenthomedirectory -ne $null)) {
      
            takeown.exe/f "$CurrentHomeDirectory" /a /r /d y /skipsl
            cacls.exe "$CurrentHomeDirectory" /e /t /g administrators:f
      
            remove-item -path $CurrentHomeDirectory -force -recurse
            $CurrentUser | remove-aduser
      } else {
            write-output $currentuser | select-object -property samaccountname,homeDirectory
      }
}
0
 

Author Comment

by:kuzum
ID: 40251422
I added this line to code
import-module -name ActiveDirectory -erroraction silentlycontinue
$Users = get-content -path "C:\temp\testadusers.txt"

$Users | foreach-object {
      $CurrentUser = Get-ADUser -identity $_ -properties homeDirectory
      $CurrentHomeDirectory = $($CurrentUser).homedirectory

      if ((test-path -path $currenthomedirectory) -and ($currenthomedirectory -ne $null)) {
      
             write-host "$currentHomeDirectory"

         takeown.exe/f "$CurrentHomeDirectory" /a /r /d y
            cacls.exe "$CurrentHomeDirectory" /e /t /g administrators:f
      
            remove-item -path $CurrentHomeDirectory -force -recurse
            $CurrentUser | remove-aduser
      } else {
            write-output $currentuser | select-object -property samaccountname,homeDirectory
      }
}
and out come was with the same error and this one line  information \\servername\aait$
0
 

Author Comment

by:kuzum
ID: 40252136
script seems to be doing something, below is the result, can you please confirm the abouve code please?

\\servername\AMBR$
takeown.exe/f : The term 'takeown.exe/f' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a
path was included, verify that the path is correct and try again.
At line:12 char:10
+          takeown.exe/f "$CurrentHomeDirectory" /a /r /d y
+          ~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (takeown.exe/f:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
 
cacls.exe : The network name cannot be found.
At line:13 char:3
+         cacls.exe "$CurrentHomeDirectory" /e /t /g administrators:f
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (The network name cannot be found.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
0
 
LVL 25

Expert Comment

by:Coralon
ID: 40252241
There should be a space between takeown.exe and the /f  

DId you put in the write-host commands to make sure the $CurrentHomeDirectory is pulling correctly?

Coralon
0
 

Author Comment

by:kuzum
ID: 40252284
import-module -name ActiveDirectory -erroraction silentlycontinue
$Users = get-content -path "C:\temp\testadusers.txt"

$Users | foreach-object {
      $CurrentUser = Get-ADUser -identity $_ -properties homeDirectory
      $CurrentHomeDirectory = $($CurrentUser).homedirectory

      if ((test-path -path $currenthomedirectory) -and ($currenthomedirectory -ne $null)) {
      
             write-host "$currentHomeDirectory"

         takeown.exe /f "$CurrentHomeDirectory" /a /r /d y
            cacls.exe "$CurrentHomeDirectory" /e /t /g administrators:f
      
            remove-item -path $CurrentHomeDirectory -force -recurse
            $CurrentUser | remove-aduser
      } else {
            write-output $currentuser | select-object -property samaccountname,homeDirectory
      }

RESULT:
\\LONNRFS01V\USER$\USER1\AMC
takeown.exe/f : The term 'takeown.exe/f' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a
path was included, verify that the path is correct and try again.
At line:12 char:10
+          takeown.exe/f "$CurrentHomeDirectory" /a /r /d y
+          ~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (takeown.exe/f:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
processed dir: \\fileserver\USER$\USER1\AMC
processed file: \\fileserver\USER$\USER1\AMC\0
processed file: \\fileserver\USER$\USER1\AMC\967PROF.XLS
0
 

Author Comment

by:kuzum
ID: 40252326
after space between takeown.exe and the /f and write host line as shown in the abouve code this is what script does now
it is going through all the files belongs to user. Is this what it should do?
 SUCCESS: The file (or folder):  "\\servername\APAT$\APAT\ilias pc\staurakaki-ag.stefanos-wc(2).lnk" now owned by the administrators group.

SUCCESS: The file (or folder): "\\servername\APAT$\APAT\ilias pc\TAXYTHTA GIA ZWH.lnk" now owned by the administrators group.
0
 

Author Comment

by:kuzum
ID: 40255508
any ideas please?
0
 
LVL 25

Expert Comment

by:Coralon
ID: 40257377
That is correct.  And the subsequent lines are showing cacls.exe doing it's step.

It sounds like it is doing exactly what you need it to.

Coralon
0
 

Author Comment

by:kuzum
ID: 40257774
Ok. As last, can you please add log files to be created in the script? Would be very useful to see what has successfully deleted and what hasn't. Is it possible please?
Thanks for help
0
 
LVL 25

Accepted Solution

by:
Coralon earned 2000 total points
ID: 40259813
Just add a start-transcript to the beginning of the script and a stop-transcript at the end.  

So.. the top line of the script will be 'start-transcript -path c:\temp\homedelete.log' (or whatever path & name you want.  And the last line of the script will be stop-transcript.

Coralon
0
 
LVL 3

Expert Comment

by:Liam Somerville
ID: 40273447
You may run into issues with the transcript as PowerShell is a bit odd in where it writes the output. If you find you're missing information from your transcript, add an | Out-Default to the end of the missing commands.
0
 

Author Comment

by:kuzum
ID: 40273600
sorry Liam did not quite understand that? Can you please add that bit to my code and send it to me so I can try please?
script is working fine but taking too long as it needs to take ownership of everything in users folders.
thanks
0
 
LVL 3

Expert Comment

by:Liam Somerville
ID: 40273631
Something like this. It may not  be necessary, but I've run into it a few times and it makes for less than useful transcripts.

Start-Transcript -Path 'C:\temp\log.txt'
$Users = get-content -path "C:\temp\testadusers.txt"

$Users | foreach-object {
      $CurrentUser = Get-ADUser -identity $_ -properties homeDirectory
      $CurrentHomeDirectory = $($CurrentUser).homedirectory

      if ((test-path -path $currenthomedirectory) -and ($currenthomedirectory -ne $null)) {
      
             write-host "$currentHomeDirectory"  | Out-Default

         takeown.exe /f "$CurrentHomeDirectory" /a /r /d y 
            cacls.exe "$CurrentHomeDirectory" /e /t /g administrators:f  | Out-Default
      
            remove-item -path $CurrentHomeDirectory -force -recurse
            $CurrentUser | remove-aduser  | Out-Default
      } else {
            write-output $currentuser | select-object -property samaccountname,homeDirectory  | Out-Default
      }
Stop-Transcript

Open in new window

0
 

Author Comment

by:kuzum
ID: 40273741
thank you, can you please tell me what it does exactly?
0
 
LVL 3

Expert Comment

by:Liam Somerville
ID: 40273783
TThis post does a pretty good job of explaining. Essentially it makes sure that all of the things your script does ends up in the transcript.
0

Featured Post

Restore individual SQL databases with ease

Veeam Explorer for Microsoft SQL Server delivers an easy-to-use, wizard-driven interface for restoring your databases from a backup. No expert SQL background required. Web interface provides a complete view of all available SQL databases to simplify the recovery of lost database

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This process allows computer passwords to be managed and secured without using LAPS. This is an improvement on an existing process, enhanced to store password encrypted, instead of clear-text files within SQL
Wouldn't it be nice if objects in Active Directory automatically moved into the correct Organizational Units? This is what AutoAD aims to do and as a plus, it automatically creates Sites, Subnets, and Organizational Units.
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
Screencast - Getting to Know the Pipeline

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question