powershell script to delete AD accounts

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
kuzumAsked:
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.

CoralonCommented:
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
Premkumar YogeswaranAnalyst II - System AdministratorCommented:
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
kuzumAuthor Commented:
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
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

CoralonCommented:
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
kuzumAuthor Commented:
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
kuzumAuthor Commented:
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
CoralonCommented:
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
kuzumAuthor Commented:
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
CoralonCommented:
Yes.. but on your Windows 7 machine, is the powershell prompt elevated, or is UAC turned off?

Coralon
0
kuzumAuthor Commented:
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
kuzumAuthor Commented:
any suggestion please?
0
kuzumAuthor Commented:
may be VB script is better idea for this task?
0
CoralonCommented:
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
kuzumAuthor Commented:
Hi,

I noticed some of the acocunts do not have  holme directory. What should I do in this case?
0
CoralonCommented:
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
kuzumAuthor Commented:
my AD servers are 2008 and file servers ( home drives) are 2003. Can this still work?
thanks
0
CoralonCommented:
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
kuzumAuthor Commented:
thanks Coralon, I am running it from my windows 7 machine. is that ok?
0
CoralonCommented:
As long as you have the RSAT tools for Active Directory installed.

Coralon
0
kuzumAuthor Commented:
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
kuzumAuthor Commented:
any ideas? thanks
0
kuzumAuthor Commented:
--------------------------------------------------------------------------------

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
CoralonCommented:
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
kuzumAuthor Commented:
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
kuzumAuthor Commented:
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
kuzumAuthor Commented:
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
CoralonCommented:
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
kuzumAuthor Commented:
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
kuzumAuthor Commented:
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
kuzumAuthor Commented:
any ideas please?
0
CoralonCommented:
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
kuzumAuthor Commented:
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
CoralonCommented:
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

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
Liam SomervilleSenior Security ConsultantCommented:
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
kuzumAuthor Commented:
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
Liam SomervilleSenior Security ConsultantCommented:
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
kuzumAuthor Commented:
thank you, can you please tell me what it does exactly?
0
Liam SomervilleSenior Security ConsultantCommented:
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
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.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.