Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Credentials to Service with PowerShell

Hi when automating the creation of services with PowerShell as part of a bigger script, i have come across a stumbling block with the credential side of the task:

Running:

 New-Service -Credential $dmhostcred -BinaryPathName "C:\$AppInstance\Data.Service.exe" -DisplayName "DataService $AppInstance Host Service" -StartupType Automatic -Description "Data $AppInstance Host_Service" -Name "Data Service $AppInstance Host Service"

Wont work. It WILL create the service but wont add in the password into the credentials field for the service. The creds are stored using the Get-Credential command in a variable earlier on in the script.

Obviously i dont want passwords stored as a string/in raw form in script.

To get around this, I found another method for achieving this, which worked, but involves a lot of beating around the bush:

$serviceName = "Data $AppInstance Host"
        $hostdescription = "Data Host"
        $exePath = "C:\Path to App Folder\Service.exe"
        $userName = "$host"
        $securePassword = convertto-securestring -String "$password" -AsPlainText -Force  
        $credentialsObject = new-object -typename System.Management.Automation.PSCredential -argumentlist $userName, $securePassword
        New-Service -BinaryPathName $exePath -Name $serviceName -Description $hostdescription -Credential $credentialsObject -DisplayName $serviceName -StartupType Automatic

This does work but when creating multiple services, this is a nightmare, and i have to store the password as a string in another variable, i hope you can appreciate - I'm trying to cut down on having to re-enter the same details repeatedly, neither of these solutions work for setting up service accounts in an automated fashion.

Any help on how to achieve this in a much more straightforward manner would be greatly appreciated.

Thanks, Roy

like image 810
Royston Avatar asked Jan 26 '26 05:01

Royston


1 Answers

$user = "myUser"
$server = "myServer"
$file = ".\password.txt"

# Store password in a file at the beginning of your script
Read-Host "Enter Password for $user on $server" -AsSecureString | ConvertFrom-SecureString | Out-File $file


# Retrieve password later on, whenever you need it
$credential = New-Object -TypeName System.Management.Automation.PSCredential($user, (Get-Content $file | ConvertTo-SecureString))
like image 97
David Brabant Avatar answered Jan 29 '26 01:01

David Brabant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!