2015-10-26 52 views
0

當我以管理員身份運行時,我的代碼完美運行。但它給我一個錯誤,當我運行它作爲客人:如何以管理員身份運行Power shell

發生內部錯誤。

有什麼辦法可以配置運行電源shell作爲管理員編程?

string shellUri = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell"; 
string password = "****"; 
System.Security.SecureString securePW = new System.Security.SecureString(); 
foreach (char c in password) 
     securePW.AppendChar(c); 
securePW.MakeReadOnly(); 
string domainAndUsername = @"192.168.1.113\***"; 
string remoteMachineName = "****"; 
PSCredential remoteCredential = new PSCredential(domainAndUsername, securePW); 
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, remoteMachineName, 5985, "/wsman", shellUri, remoteCredential); 

using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo)) //_Error Here_// 

我發現了一些解決方案,但他們都老了,他們不工作了:S

+0

是否這個stackoverflow後回答幫助? http://stackoverflow.com/questions/7690994/powershell-running-a-command-as-administrator – Dome

+0

不,它不會:( –

+0

也許你可以創建一個Windows Scheduled Task來執行PowerShell腳本並讓它運行與具有管理員權限的特定用戶帳戶關聯。 – DarkLite1

回答

1

如果您使用以下使用,你可以作爲管理員身份運行程序:

var processStartInfo = new ProcessStartInfo("powershell") 
      { 
       UseShellExecute = true, 
       CreateNoWindow = true, 
       Verb = "runas", 
       //UserName = username, 
       //Password = MakeSecureString(password) 
      }; 
      var exec = Process.Start(processStartInfo); 
      exec?.WaitForExit(0); 

如果你不不想提示,那麼你將不得不改變UAC。您可以將參數傳遞給過程對象。

相關問題