Link to home
Start Free TrialLog in
Avatar of SquigglyMonkey
SquigglyMonkey

asked on

powershell script to unlock local accounts

I am looking for code examples for powershell to find and then unlock local accounts (not AD accounts)

Thanks!
Avatar of Vasil Michev (MVP)
Vasil Michev (MVP)
Flag of Bulgaria image

Avatar of SquigglyMonkey
SquigglyMonkey

ASKER

I found this earlier today, it was written by someone else, or copied by one of them, it's almost identical. After loading the module I can't get the 'enable' to actually enable.
Try..
$Username = "TestUser"
$Computer = "ServerA"
[ADSI]$user = [ADSI] "WinNT://$Computer/$Username"
If ($user.IsAccountLocked -ne $null){
	IF ($user.IsAccountLocked -ne $false) {
		Try {
		$user.IsAccountLocked = $False
		$user.SetInfo()
		"Unlocked the account $Username"
		}
		Catch {
		"Error whle Unlocking the account $Username : $($_.Exception.Message)"
		}
	}
	Else{
	"The account $Username is not locked"
	}
}
Else{
"Unable to find user $Username"
}

Open in new window

Thanks Subsun, I am not sure that is the path I want to go down.
I need to run a script nightly, find locked accounts and unlock them. All of them will be local accounts (not Domain accounts) on a single server.

This is the code I was working on to accomplish it, using the local admin modules from Microsoft:

Get-LocalUser | Where-Object {$_.LockedOut -eq $True} | unlock-LocalUser
I never used this module so I am not sure if it works.. You can also use WMI to do this task..
Here is a sample code which will unlock all locked local accounts in computer..
Get-WmiObject -Class Win32_UserAccount | 
 ?{$_.LocalAccount -eq $True -and $_.Lockout -eq $True}| 
 % {
 $User = $_
 $User.Lockout = $false
 $User.Put()
}

Open in new window

Get-WmiObject -Class Win32_UserAccount
This pulls every name in the Active Directory.... that's like 10K+
You need to add filter..
Get-WmiObject -Class Win32_UserAccount | 
 ?{$_.LocalAccount -eq $True -and $_.Lockout -eq $True}

Open in new window

Well, when I run it, with the filter, it chugs for like 10 minutes, till I kill it.
So when I ran the first line alone, I could see it was loading thousands of accounts.
I just tried it and it works for me.. Did you try it on any other server and see if it shows same issue?
ASKER CERTIFIED SOLUTION
Avatar of SubSun
SubSun
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That works great! Thank you.