2

我正在使用 PowerShell 命令编写一个 web 服务,我想在本地计算机和远程计算机上启动和停止服务。

在远程计算机上启动和停止服务不是问题。我使用 WmiObject 执行此操作,如下所示。

如果我想启动本地服务,它会说我没有权限。

如果我想启动本地服务,我不能将 WmiObject 与 Credentials 一起使用。

我该怎么做才能以管理员权限启动服务?

我的脚本(strScriptText):

$username = "domain\administrator"
$pw = convertto-securestring "password" -asplaintext -force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $pw
$computername = "serverAB"
if ( $computername.Contains("serverAB")){(Get-WmiObject -class Win32_Service -filter "name='AppIDSvc'").startservice().returnvalue}
else {(Get-WmiObject -class Win32_Service -ComputerName $computername -Credential $cred -filter "name='AppIDSvc'").startservice().returnvalue}

VB:

 runspace = RunspaceFactory.CreateRunspace()
        runspace.Open()
 pipeline = runspace.CreatePipeline()

pipeline.Commands.AddScript(strScriptText)
                pipeline.Commands.Add("Out-String")
4

1 回答 1

0

您不能尝试通过 PowerShell 使用旧的 .NET 方法。

# Create an authentication object
$ConOptions = New-Object System.Management.ConnectionOptions
$ConOptions.Username = "dom\jpb"
$ConOptions.Password = "pwd"
$ConOptions.EnablePrivileges = $true
$ConOptions.Impersonation = "Impersonate"
$ConOptions.Authentication = "Default"

# Creation of a rmote or local process
$scope = New-Object System.Management.ManagementScope("\\dom.fr\root\cimV2", $ConOptions)
$ObjectGetOptions = New-Object System.Management.ObjectGetOptions($null, 
                                                          [System.TimeSpan]::MaxValue, $true)
$proc = New-Object System.Management.ManagementClass($scope, 
                                      "\\dom.fr\ROOT\CIMV2:Win32_Process", $ObjectGetOptions)

# Equivalent to : 
# $proc = [wmiclass]"\\.\ROOT\CIMV2:Win32_Process"
# $res = $proc.Create("cmd.exe")
于 2012-10-17T12:26:05.620 回答