I am running the below but can't work out why I get access denied at the call to New-Service:
param(
[string]$serviceName,
[string]$exePath,
[string]$username,
[string]$password
)
"Attempting to install service '$serviceName' - '$exePath'"
$secpassword = convertto-securestring -String $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($username, $secpassword)
$existingService = Get-WmiObject -Class Win32_Service -Filter "Name='$serviceName'"
if ($existingService)
{
"'$serviceName' exists already. Stopping."
Stop-Service $serviceName
"Waiting 3 seconds to allow existing service to stop."
Start-Sleep -s 3
$existingService.Delete()
"Waiting 5 seconds to allow service to be un-installed."
Start-Sleep -s 5
}
"Installing the service."
New-Service -BinaryPathName $exePath -Name $serviceName -Credential $cred -DisplayName $serviceName -StartupType Automatic
"Installed the service."
"Starting the service."
Start-Service $serviceName
"Complete."
I have double checked the credentials I pass to the script of course, using 'adminstrator' and 'workgroup\administrator' for the username. I am actually logged in to the machine as administrator.
Have you tried using an elevated Powershell console? Right-Click Powershell > Run as Administrator. This issue happens a lot when running scripts that modify system settings, specially in Windows 2012.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With