Windows – Powershell service creation with ad credentials logon error

active-directorypowershellservicewindowswindows-server-2008

Powershell service creation with AD credentials issue

I use the script below to create a service running with AD credentials.

However when I run it I get an error message (also below).

If I then edit the service and enter exactly the same credentials through the services.mmc snapin it works? How can I fix this?

Error Message

Windows could not start the "SamsService" service on local computer.
Error 1069: The service did not start due to a logon failure.

Powershell

$serviceName = "SamsService"
$exePath = "c:\services\service.exe"
$userName = "mydomain\serviceuser"
$securePassword = convertto-securestring -String "1a_really_$trong_password1" -AsPlainText -Force  
$credentialsObject = new-object -typename System.Management.Automation.PSCredential -argumentlist $userName, $securePassword

New-Service -BinaryPathName $exePath -Name $serviceName -Credential $credentialsObject -DisplayName $serviceName -StartupType Manual 

Best Answer

Powershell string interpolation caught me out

My password generator creates really strong passwords that always includes $

I had not recognised that the $ was being interpolated in the password string to mean a variable. After escaping the $ with ` the above code works a treat.