具有管理员权限的VB.NET中的Powershell

时间:2012-10-17 09:51:30

标签: vb.net powershell administrator

我正在编写一个带有PowerShell命令的Web服务,我希望在本地计算机和远程计算机上启动和停止服务。

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

如果我想启动本地服务,则表示我没有权限。

如果我想启动本地服务,我无法使用带有凭据的WmiObject。

如何使用管理员权限启动服务?

我的脚本(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")

1 个答案:

答案 0 :(得分: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")