Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Install windows service via Powershell on Win2012 - Access Denied

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.

like image 571
Myles McDonnell Avatar asked Mar 15 '23 04:03

Myles McDonnell


1 Answers

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.

like image 173
Aresius Avatar answered Apr 26 '23 16:04

Aresius