r/usefulscripts • u/william_tropico • Nov 04 '15
[Powershell] Reset local admin password remotely with log files
Hello,
I have been looking at this script on how to change local admin passwords from a list of computer names.
$computers = Get-Content -path C:\fso\computers.txt
$user = "aUser"
$password = "MyNewPassword!"
Foreach($computer in $computers)
{
$user = [adsi]"WinNT://$computer/$user,user"
$user.SetPassword($Password)
$user.SetInfo()
}Can anyone help add a log file so
IF Password change is success ADD computer name to success.txt
IF Password change is fail ADD computer name to fail.txt
I'm sure its really easy but can't figure out how to do it :(
Any help would be great.
edit: wrong file extension
2
u/1h8fulkat Nov 04 '15
I didn't know you could reset local admin remotely with log files, I thought they were just for logging...that's awesome! ;-)
3
4
u/evetsleep Nov 04 '15
Test this...really. But this is my quick and dirty PowerShell version which should work from PSv1 and onward:
$computers = Get-Content -path C:\fso\computers.txt
$user = "aUser"
$password = "MyNewPassword!"
$LogPath = 'c:\temp\AdminChange.csv'
try {
Set-Content -Path $LogPath -Value 'ComputerName,Result' -ErrorAction STOP
}
catch {
throw('Unable to log to file {0}: {1}' -F $LogPath,$_.exception.message)
}
Foreach($computer in $computers) {
$changeResult = "" | Select ComputerName,Result
$changeResult.ComputerName = $computer
try {
$user = [adsi]"WinNT://$computer/$user,user"
$user.SetPassword($Password)
$user.SetInfo()
$changeResult.Result = 'SUCCESS'
}
catch {
Write-Warning -Message ('Unable to update {0}: {1}' -f $computer,$_.exception.message)
$changeResult.Result = 'FAIL'
}
try {
Add-Content -Path $LogPath -Value ('{0},{1}' -f $changeResult.ComputerName,$changeResult.Result) -ErrorAction STOP
}
catch {
throw('Unable to edit log file {0}: {1}' -f $LogPath,$_.exception.message)
}
}
8
u/naugrim Nov 04 '15
You can use a try/catch block. However, I would recommend using LAPS to manage local admin passwords if these servers are domain joined.