我使用C#Windows服务模板(使用VS2013的.Net 4.5.1框架)创建了一个Windows服务(比如名为foo
)。
完成项目后,我想使用Powershell
将其安装到我的电脑上。我用来安装服务的脚本来自这个page。 (礼貌和信任:Phil Campbell先生):
$serviceName = "foo"
$exePath = "C:\Program Files\foo\foo.exe"
$username = "someUser"
$password = convertto-securestring -String "somePassword" -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
$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 uninstalled."
Start-Sleep -s 5
}
"Installing the service."
New-Service -BinaryPathName $exePath -Name $serviceName -Credential $cred -DisplayName $serviceName -StartupType Automatic
"Installed the service."
$ShouldStartService = Read-Host "Would you like the '$serviceName ' service started? Y or N"
if($ShouldStartService -eq "Y")
{
"Starting the service."
Start-Service $serviceName
}
"Completed."
但是,我收到以下错误:
CategoryInfo:PermissionDenied:(foo:String)[New-Service], ServiceCommandException + FullyQualifiedErrorId: CouldNotNewService,Microsoft.PowerShell.Commands.NewServiceCommand
在这一行:
在第22行:1:1 + New-Service -BinaryPathName $ exePath -Name $ serviceName -Credential $ ...
为什么会这样?我们如何解决这个问题?
注意:我的用户someUser
拥有管理员权限(或者更确切地说,我的用户 管理员)和我Run Powershell as Administrator
。