【问题标题】:Powershell New-Service gives permission deniedPowershell New-Service 授予权限被拒绝
【发布时间】:2019-03-10 22:35:00
【问题描述】:

借鉴微软示例代码:

function myService() {
  New-Service -Name "MyService" -BinaryPathName "c:\windows\system32\svchost.exe -k netsvcs"
}

Start-Process -FilePath powershell.exe -Verb RunAs -Wait -ArgumentList '-Command',"$(myService)"

New-Service:由于以下错误无法创建服务:访问被拒绝。

这很奇怪,因为我认为 -RunAs 让我成为管理员。

我还需要做些什么来启动服务吗?

【问题讨论】:

  • 你能以管理员身份运行 PowerShell 本身吗?
  • @HariHaran 我可以在以管理员身份运行的函数中运行其他命令。这与以管理员身份运行 powershell 本身是一样的吗?

标签: powershell


【解决方案1】:

这是因为您在当前的 powershell 实例中运行 myService 函数,而不是在您打开的新实例中。 $(myService) 是一个表达式,因为它被 double "包围,所以在当前的 powershell 实例中运行,并将结果传递给 Start-Process 实例。

您需要将该函数作为字符串传递给 Start-Process

Start-Process -FilePath powershell.exe -Verb RunAs -Wait -ArgumentList '-Command',"function myService() {New-Service -Name 'MyService' -BinaryPathName 'c:\windows\system32\svchost.exe -k netsvcs'};myService"

你也可以事先把函数变成一个字符串,然后用双引号 "

$Function1 = @"
function myService() {
    New-Service -Name 'MyService' -BinaryPathName 'c:\windows\system32\svchost.exe -k netsvcs'
}
"@
Start-Process -FilePath powershell.exe -Verb RunAs -Wait -ArgumentList '-Command',"$Function1;myService;pause"

【讨论】:

  • 如果我想将变量值传递给要在命令行上使用的函数怎么办?
  • 这听起来完全是另一个问题。但是您必须通过字符串传递所有内容,因此如果它是function myService($Name),您将是myService -name 'helloWorld'。所以像-argumentslist "function MyService($name){Function Code Here};MyService -Name 'helloWorld'"
猜你喜欢
  • 2011-10-17
  • 2011-08-28
  • 2017-05-14
  • 2018-04-04
  • 2021-10-18
  • 1970-01-01
  • 1970-01-01
  • 2014-09-27
  • 2014-10-30
相关资源
最近更新 更多