Forum Discussion
Service control manager cached credentials
Example 8: Change credential of a service
This example changes the credentials that are used to manage a service.
$credential = Get-Credential
Set-Service -Name Schedule -Credential $credential
Get-Credential prompts for a username and password, and stores the credentials in the $credential variable. Set-Service uses the Name parameter to specify the Schedule service. The Credential parameter uses the $credential variable and updates the Schedule service.
You could use https://pscustomobject.github.io/powershell/howto/PowerShell-Create-Credential-Object/ to use it in a script (SecureString)
I believe SC.exe and/or WMI should be able to update the password.
- LainRobertsonApr 13, 2022Silver Contributor
Hi, Animesh.
As you've said, you can look to calling an external application such as sc.exe or leverage WMI.
If you're really keen on a native PowerShell approach, and in the specific context of an approach that will work with version 4.0, you'd be looking to make use of the platform invoke (commonly shortened to "p/invoke") method.
Here's a good example on stackoverflow for using the p/invoke approach specifically with Windows services.
Eventually, you'd be looking to leverage the ChangeServiceConfigW function to set the password. Most of the other parameters can simply be left as null, so it's not as bad as it looks.
c# - change windows service password - Stack Overflow
You'd be wise to wrap this in a static class definition but it's not strictly necessary.
Cheers,
Lain