Repeatability is important! Right alongside that, in my opinion, is efficiency. A recent task required me to set up several Application Services setups, including setting the log on account and password. I could have done all of these manually; however, I found it more efficient and repeatable to set up a script to handle the setup.
I won’t get into the portion for the setup of the services; I’ll communicate a few ways to set a Windows Service Log On Account and Password with PowerShell.
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()