借用Microsoft示例代码:
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)"
新服务:由于以下错误,无法创建服务:访问被拒绝。
这很奇怪,因为我认为-RunAs
让我成为管理员。
我还需要做些什么才能开始服务吗?
这是因为您在当前的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"
你也可以把这个函数变成一个字符串,然后用双qoutes传递它“
$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"