Powershell script to change service account

I created a text file "changeserviceaccount.ps1" containing the following script:

$account="domain\user"
$password="passsword"
$service="name='servicename'"

$svc=gwmi win32_service -filter $service
$svc.StopService()
$svc.change($null,$null,$null,$null,$null,$null,$account,$password,$null,$null,$null)
$svc.StartService()

I used this as part of by post-build command line during the development of a windows service:

Visual Studio: Project properties\Build Events

Pre-build event command line:

"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\installutil.exe" myservice.exe /u

Post-build event command line:

"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\installutil.exe" myservice.exe
powershell -command - < c:\psscripts\changeserviceaccount.ps1

The PowerShell 6 version of Set-Service now has the -Credential parameter.

Here is an example:

$creds = Get-Credential
Set-Service -DisplayName "Remote Registry" -Credential $creds

At this point, it is only available via download via GitHub.

Enjoy!


Bit easier - use WMI.

$service = gwmi win32_service -computer [computername] -filter "name='whatever'"
$service.change($null,$null,$null,$null,$null,$null,$null,"P@ssw0rd")

Change the service name appropriately in the filter; set the remote computer name appropriately.


I wrote a function for PowerShell that changes the username, password, and restarts a service on a remote computer (you can use localhost if you want to change the local server). I've used this for monthly service account password resets on hundreds of servers.

You can find a copy of the original at http://www.send4help.net/change-remote-windows-service-credentials-password-powershel-495

It also waits until the service is fully stopped to try to start it again, unlike one of the other answers.

Function Set-ServiceAcctCreds([string]$strCompName,[string]$strServiceName,[string]$newAcct,[string]$newPass){
  $filter = 'Name=' + "'" + $strServiceName + "'" + ''
  $service = Get-WMIObject -ComputerName $strCompName -namespace "root\cimv2" -class Win32_Service -Filter $filter
  $service.Change($null,$null,$null,$null,$null,$null,$newAcct,$newPass)
  $service.StopService()
  while ($service.Started){
    sleep 2
    $service = Get-WMIObject -ComputerName $strCompName -namespace "root\cimv2" -class Win32_Service -Filter $filter
  }
  $service.StartService()
}