The Set-Service cmdlet changes the properties of a service, along with the starting and stopping of a service.

Before setting the log-on account information for a service, we need to capture the credentials. The credentials can come from user input:

# Prompt for credentials
$Credential = Get-Credential

# Prompt for credentials with message
$Credential = Get-Credential -UserName domain\user -Message 'Enter Password for Service Account'

or the credentials may be in the contents of the script:

$UserName = 'admin'
$Password = 'password'
$SecurePassword = ConvertTo-SecureString $Password -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ($UserName,$SecurePassword)

Once the credentials are captured, they are set for the service:

# Enter the name of the service to set; i.e. EventLog
$ServiceName = 'EventLog'

# Stop the service
Set-Service -Name $ServiceName -Status Stopped

# Set the service credentials
Set-Service -Name $ServiceName -Credential $Credential

# Start the service
Set-Service -Name $ServiceName -Status Running

The Get-Service cmdlet retrieves the properties of a service.

If you’re using an earlier version of PowerShell and do not have the -Credential parameter available, you can use the gwmi / Get-WmiObject cmdlet:

$account = "<the account name>"
$password = "<the account password>"
$servicename = "name='<the service name>'"

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