2013-06-12 94 views
3

我需要執行一對夫婦從C#PowerShell命令的,而我使用此代碼調用PowerShell命令用不同的憑據

Runspace rs = RunspaceFactory.CreateRunspace(); 
rs.Open(); 
PowerShell ps = PowerShell.Create(); 
ps.Runspace = rs; 
ps.AddCommand("Add-PSSnapin").AddArgument("Citrix*"); 
ps.Invoke(); 
// other commands ... 

這工作正常,但現在沒有足夠的權限來使用PowerShell用戶應執行此應用程序。有沒有辦法用不同的憑據執行PowerShell代碼? 我的意思是這樣

var password = new SecureString(); 
Array.ForEach("myStup1dPa$$w0rd".ToCharArray(), password.AppendChar); 
PSCredential credential = new PSCredential("serviceUser", password); 
// here I miss the way to link this credential object to ps Powershell object... 
+0

如果還沒解決,請問以下文章回答你的問題? [選自C尖銳應用運行的powershell腳本] [1] [1]:http://stackoverflow.com/questions/11120452/run-powershell-script-from-c-sharp-application –

回答

1

未經測試的代碼...但是這應該爲你工作。我使用類似的東西來運行遠程PowerShell(只需設置WSManConnectionInfo.ComputerName)。

public static Collection<PSObject> GetPSResults(string powerShell, PSCredential credential, bool throwErrors = true) 
{ 
    Collection<PSObject> toReturn = new Collection<PSObject>(); 
    WSManConnectionInfo connectionInfo = new WSManConnectionInfo() { Credential = credential }; 

    using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo)) 
    { 
     runspace.Open(); 
     using (PowerShell ps = PowerShell.Create()) 
     { 
      ps.Runspace = runspace; 
      ps.AddScript(powerShell); 
      toReturn = ps.Invoke(); 
      if (throwErrors) 
      { 
       if (ps.HadErrors) 
       { 
        throw ps.Streams.Error.ElementAt(0).Exception; 
       } 
      } 
     } 
     runspace.Close(); 
    } 

    return toReturn; 
}