在 Win2012 上通过 Powershell 安装 Windows 服务 - 拒绝访问

Myl*_*ell 4 powershell windows-server-2012

我正在运行以下命令,但无法弄清楚为什么在调用 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."
Run Code Online (Sandbox Code Playgroud)

我已经仔细检查了我传递给脚本的凭据,使用“adminstrator”和“workgroup\administrator”作为用户名。我实际上以管理员身份登录到机器。

小智 7

您是否尝试过使用提升的 Powershell 控制台?右键单击 Powershell > 以管理员身份运行。这个问题在运行修改系统设置的脚本时经常发生,特别是在 Windows 2012 中。