PowerShell New-Service – Using User Credentials in Windows

powershellwindows

I am trying to add a service to my windows computer by using the command

New-Service -Name TestWorkerService -BinaryPath "C:\Test\TestingService\Service.exe" -Credential "" -Description "Testing Service" -DisplayName "Testing Service" -StartupType Automatic

(yes, I know I have -Credential set as "")

I am not sure what value should go for -Credential I have tried just the username i've input into Powershell $env:computername and $env:UserName and I've used for -Credential the value I get from both of the above commands and added a "" between them, but I keep getting the error of

Can not be created due to the following error: The account name is invalid or does not exist, or the password is invalid for the account name spsecified

What is the proper format the New-Service is expecting -Credential in?

EDIT
I tried to manually set it up, but I get the errors below. These are the commands I used (pressing enter after each line)

$username = "username"
$password = "password"
$securepassword = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCrednetial ($username, $securepassword)

enter image description here

enter image description here

Best Answer

It needs an object of type PSCredential. It can be created manually using the command Get-Credential.

There are other ways, but they are a bit tricky because the password needs to be passed in as a SecureString.

You can find how to programmatically build a PSCredential object here.


Sample code:

$username = "username"
$password = "password"
$securepassword = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($username, $securepassword)

New-Service [...] -Credential $cred
Related Topic