2012-10-17 55 views
2

我正在用PowerShell命令編寫一個web服務,我想在本地計算機和遠程計算機上啓動和停止服務。帶有管理權限的VB.NET中的Powershell

在遠程計算機上啓動和停止服務不是問題。我用下面的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") 

回答

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") 
+0

感謝您的答案,但我認爲那不是我想做的事情。這只是打開一個CMD窗口... – Senni

+0

嗯,這是展示如何編寫WMI請求證書的例子,這就是你正在找 ? – JPBlanc

+0

不,您可以看到I#m已經在使用WMI對象的憑證。但是如果我想控制本地機器上的服務,WMI對象不會接受憑據。如果是這種情況,我使用非管理用戶登錄,並且沒有權限啓動該服務,但我想啓動它。所以必須有一種方法來控制它。但是怎麼樣?! – Senni