Ever wanted to change the password of the local administrator account (or any local user account for that matter) in .net? Here's how: Code is in white on blue!
Make sure you import
System.DirectoryServices
Imports System.DirectoryServices
First things first we need to check to see if the computer is turned on, lets try a quick ping
Dim pinger As New Net.NetworkInformation.Ping
Try
Dim result = pinger.Send(MachineName)
If result.Status <> Net.NetworkInformation.IPStatus.Success Then
'unable to connect
Return False
End If
Catch ex As Exception
'unable to connect
Return False
End Try
Nothing complicated about that and you could enhance it to provide some feedback
Now to connect to the machine for this use
DirectoryEntry, its got quite a few parameters/overloads but for this we're only interested in:
Address of the computer we're trying to connect to
Username of the account we're going to be using to change the password -must have the ability to change a local user password so if you use a AD account make sure its part of the admin group on the target machine
Password of the above account
Authentication -the machine won't let you change the password if its not a secure connection!
All together looks like:
Dim de As New DirectoryEntry(String.Format("WinNT://{0}", MachineName), "mydomain\accountname", " accountpassword", AuthenticationTypes.Secure)
quick check to see if its worked
If de Is Nothing Then
'couldn't connect
Return False
End If
Now, technically you should be able to give it the path WinNT://machinename/Nameoftheaccount but i couldn't get this to work, just throws 80005000 errors so....
Query the directory entry to find the account we're looking for, in this case: Administrator
Dim admin = de.Children.Find("Administrator")
If admin Is Nothing Then
'couldn't connect or find account
Return False
End If
Finally to change the password: Bear in mind that the password must conform to any complexity requirements you have setup!
Try
admin.Invoke("SetPassword", "New password")
admin.CommitChanges()
'Done!
Catch ex As Exception
Return False
End Try
The code in full as a function:
Public Function ChangeLocalUserPassword(ByVal MachineName As String, ByVal LocalUser As String, ByVal Pass As String) As Boolean
Dim pinger As New Net.NetworkInformation.Ping
Try
Dim result = pinger.Send(MachineName)
If result.Status <> Net.NetworkInformation.IPStatus.Success Then
'unable to connect
Return False
End If
Catch ex As Exception
Return False
End Try
Dim de As New DirectoryEntry(String.Format("WinNT://{0}", MachineName), "mydomain\accountname", " accountpassword", AuthenticationTypes.Secure)
If de Is Nothing Then
'couldn't connect or find account
Return False
End If
Dim admin = de.Children.Find(LocalUser)
If admin Is Nothing Then
'couldn't connect or find account
Return False
End If
Try
admin.Invoke("SetPassword", Pass)
admin.CommitChanges()
'Done!
Catch ex As Exception
Return False
End Try
End Function