2012-06-20 33 views
11

Sto provando a eseguire uno script PowerShell da un'applicazione C#. Lo script deve essere eseguito in uno speciale contesto utente.Eseguire PowerShell-Script dall'applicazione C#

Ho provato diversi scenari alcuni stanno lavorando alcuni non:

1. chiamata diretta da PowerShell

ho chiamato lo script direttamente da una ps-console che viene eseguito con la corretta UserCredentials.

C:\Scripts\GroupNewGroup.ps1 1 

Risultato: in esecuzione con successo lo script.

2. da un'applicazione C# console

ho chiamato lo script da un C# ConsoleApplication che è iniziato sotto i UserCredentials corrette.

Codice:

string cmdArg = "C:\\Scripts\\GroupNewGroup.ps1 1" 
Runspace runspace = RunspaceFactory.CreateRunspace(); 
runspace.ApartmentState = System.Threading.ApartmentState.STA; 
runspace.ThreadOptions = PSThreadOptions.UseCurrentThread; 


    runspace.Open(); 

Pipeline pipeline = runspace.CreatePipeline(); 

pipeline.Commands.AddScript(cmdArg); 
pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); 
Collection<PSObject> results = pipeline.Invoke(); 
var error = pipeline.Error.ReadToEnd(); 
runspace.Close(); 

if (error.Count >= 1) 
{ 
    string errors = ""; 
    foreach (var Error in error) 
    { 
     errors = errors + " " + Error.ToString(); 
    } 
} 

Risultato: senza successo. E un sacco di eccezioni "Null-Array".

3. AC# applicazione console - codice lato impersonare

(http://platinumdogs.me/2008/10/30/net-c-impersonation-with-network-credentials)

ho chiamato lo script da corrente alternata # ConsoleApplication che è iniziato sotto i UserCredentials corretti e il codice contiene la rappresentazione .

Codice:

using (new Impersonator("Administrator2", "domain", "testPW")) 

        { 
    using (RunspaceInvoke invoker = new RunspaceInvoke()) 
{ 
    invoker.Invoke("Set-ExecutionPolicy Unrestricted"); 
} 

    string cmdArg = "C:\\Scripts\\GroupNewGroup.ps1 1"; 
    Runspace runspace = RunspaceFactory.CreateRunspace(); 
    runspace.ApartmentState = System.Threading.ApartmentState.STA; 
    runspace.ThreadOptions = PSThreadOptions.UseCurrentThread; 


     runspace.Open(); 

    Pipeline pipeline = runspace.CreatePipeline(); 

    pipeline.Commands.AddScript(cmdArg); 
    pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); 
    Collection<PSObject> results = pipeline.Invoke(); 
    var error = pipeline.Error.ReadToEnd(); 
    runspace.Close(); 

    if (error.Count >= 1) 
    { 
     string errors = ""; 
     foreach (var Error in error) 
     { 
      errors = errors + " " + Error.ToString(); 
     } 
    } 
} 

Risultati:

  • Il termine 'Get-Contact' non è riconosciuto come il nome di un cmdlet, funzione, file di script o un programma eseguibile. Controllare l'ortografia del nome o se è stato incluso un percorso, verificare che il percorso sia corretto e riprovare con .
  • Il termine "C: \ Scripts \ FunctionsObjects.ps1" non è riconosciuto come il nome di un cmdlet, una funzione, un file di script o un programma eseguibile. Controllare l'ortografia del nome, o se è stato incluso un percorso, verificare che il percorso sia corretto e riprovare.
  • Non snap-in sono stati registrati per Windows PowerShell versione 2. Microsoft.Office.Server, Version = 14.0.0.0, Culture = neutral, PublicKeyToken = 71e9bce111e9429c
  • System.DirectoryServices.AccountManagement, Version = 4.0. 0.0, Lingua = il neutro PublicKeyToken = b77a5c561934e089
  • Eccezione chiamata ".ctor" con l'argomento "1" (s):. "l'applicazione Web a http://XXXX/websites/Test4/ non è stato trovato Verificare di stato digitato correttamente l'URL.Se l'URL deve essere al servizio contenuto esistente, l'amministratore di sistema potrebbe essere necessario aggiungere un nuovo mapping richiesta URL per l'applicazione prevista."
  • Non è possibile chiamare un metodo su un'espressione null-valore. Impossibile indice in un nulla array.

Fino ad ora non v'è alcuna risposta operaia

qualcuno sa perché ci sono differenze e come risolvere il problema?

+0

qualsiasi soluzione finale con il codice sorgente completo di lavoro? – Kiquenet

+0

Evita di chiamare [RunSpace.Open() mentre impersona] (http://stackoverflow.com/a/22749094/939250). –

risposta

6

Hanno si è tentato Set-ExecutionPolicy Unrestricted

using (new Impersonator("myUsername", "myDomainname", "myPassword")) 
{ 
    using (RunspaceInvoke invoker = new RunspaceInvoke()) 
    { 
     invoker.Invoke("Set-ExecutionPolicy Unrestricted"); 
    } 
} 

Edit:

trovato questo piccolo gioiello ... http://www.codeproject.com/Articles/10090/A-small-C-Class-for-impersonating-a-User

namespace Tools 
{ 
    #region Using directives. 
    // ---------------------------------------------------------------------- 

    using System; 
    using System.Security.Principal; 
    using System.Runtime.InteropServices; 
    using System.ComponentModel; 

    // ---------------------------------------------------------------------- 
    #endregion 

    ///////////////////////////////////////////////////////////////////////// 

    /// <summary> 
    /// Impersonation of a user. Allows to execute code under another 
    /// user context. 
    /// Please note that the account that instantiates the Impersonator class 
    /// needs to have the 'Act as part of operating system' privilege set. 
    /// </summary> 
    /// <remarks> 
    /// This class is based on the information in the Microsoft knowledge base 
    /// article http://support.microsoft.com/default.aspx?scid=kb;en-us;Q306158 
    /// 
    /// Encapsulate an instance into a using-directive like e.g.: 
    /// 
    ///  ... 
    ///  using (new Impersonator("myUsername", "myDomainname", "myPassword")) 
    ///  { 
    ///   ... 
    ///   [code that executes under the new context] 
    ///   ... 
    ///  } 
    ///  ... 
    /// 
    /// Please contact the author Uwe Keim (mailto:[email protected]) 
    /// for questions regarding this class. 
    /// </remarks> 
    public class Impersonator : 
     IDisposable 
    { 
     #region Public methods. 
     // ------------------------------------------------------------------ 

     /// <summary> 
     /// Constructor. Starts the impersonation with the given credentials. 
     /// Please note that the account that instantiates the Impersonator class 
     /// needs to have the 'Act as part of operating system' privilege set. 
     /// </summary> 
     /// <param name="userName">The name of the user to act as.</param> 
     /// <param name="domainName">The domain name of the user to act as.</param> 
     /// <param name="password">The password of the user to act as.</param> 
     public Impersonator(
      string userName, 
      string domainName, 
      string password) 
     { 
      ImpersonateValidUser(userName, domainName, password); 
     } 

     // ------------------------------------------------------------------ 
     #endregion 

     #region IDisposable member. 
     // ------------------------------------------------------------------ 

     public void Dispose() 
     { 
      UndoImpersonation(); 
     } 

     // ------------------------------------------------------------------ 
     #endregion 

     #region P/Invoke. 
     // ------------------------------------------------------------------ 

     [DllImport("advapi32.dll", SetLastError=true)] 
     private static extern int LogonUser(
      string lpszUserName, 
      string lpszDomain, 
      string lpszPassword, 
      int dwLogonType, 
      int dwLogonProvider, 
      ref IntPtr phToken); 

     [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)] 
     private static extern int DuplicateToken(
      IntPtr hToken, 
      int impersonationLevel, 
      ref IntPtr hNewToken); 

     [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)] 
     private static extern bool RevertToSelf(); 

     [DllImport("kernel32.dll", CharSet=CharSet.Auto)] 
     private static extern bool CloseHandle(
      IntPtr handle); 

     private const int LOGON32_LOGON_INTERACTIVE = 2; 
     private const int LOGON32_PROVIDER_DEFAULT = 0; 

     // ------------------------------------------------------------------ 
     #endregion 

     #region Private member. 
     // ------------------------------------------------------------------ 

     /// <summary> 
     /// Does the actual impersonation. 
     /// </summary> 
     /// <param name="userName">The name of the user to act as.</param> 
     /// <param name="domainName">The domain name of the user to act as.</param> 
     /// <param name="password">The password of the user to act as.</param> 
     private void ImpersonateValidUser(
      string userName, 
      string domain, 
      string password) 
     { 
      WindowsIdentity tempWindowsIdentity = null; 
      IntPtr token = IntPtr.Zero; 
      IntPtr tokenDuplicate = IntPtr.Zero; 

      try 
      { 
       if (RevertToSelf()) 
       { 
        if (LogonUser(
         userName, 
         domain, 
         password, 
         LOGON32_LOGON_INTERACTIVE, 
         LOGON32_PROVIDER_DEFAULT, 
         ref token) != 0) 
        { 
         if (DuplicateToken(token, 2, ref tokenDuplicate) != 0) 
         { 
          tempWindowsIdentity = new WindowsIdentity(tokenDuplicate); 
          impersonationContext = tempWindowsIdentity.Impersonate(); 
         } 
         else 
         { 
          throw new Win32Exception(Marshal.GetLastWin32Error()); 
         } 
        } 
        else 
        { 
         throw new Win32Exception(Marshal.GetLastWin32Error()); 
        } 
       } 
       else 
       { 
        throw new Win32Exception(Marshal.GetLastWin32Error()); 
       } 
      } 
      finally 
      { 
       if (token!= IntPtr.Zero) 
       { 
        CloseHandle(token); 
       } 
       if (tokenDuplicate!=IntPtr.Zero) 
       { 
        CloseHandle(tokenDuplicate); 
       } 
      } 
     } 

     /// <summary> 
     /// Reverts the impersonation. 
     /// </summary> 
     private void UndoImpersonation() 
     { 
      if (impersonationContext!=null) 
      { 
       impersonationContext.Undo(); 
      } 
     } 

     private WindowsImpersonationContext impersonationContext = null; 

     // ------------------------------------------------------------------ 
     #endregion 
    } 

    ///////////////////////////////////////////////////////////////////////// 
} 
+0

Sì, ho già impostato manualmente la ExecutionPolicy. Ma l'ho provato ora in codice ma senza successo: l'ho inserito nel mio codice delle domande. – HW90

0

Several PowerShell cmddlets take a PSCredential object to run using a particular user account. Può avere uno sguardo a questo articolo - http://letitknow.wordpress.com/2011/06/20/run-powershell-script-using-another-account/

Ecco come è possibile creare l'oggetto credenziale che contiene il nome utente e la password che si desidera utilizzare:

$username = 'domain\user' 
$password = 'something' 
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList @($username,(ConvertTo-SecureString -String $password -AsPlainText -Force)) 

Una volta che hai la password pronto per l'uso in una credenziale oggetto, è possibile eseguire una serie di operazioni, ad esempio chiamare Start-Process per avviare PowerShell.exe, specificare le credenziali nel parametro -Credential o Invoke-Command per richiamare un comando "remoto" localmente, specifying the credential in the -Credential parameter, oppure è possibile chiamare Inizio lavoro per eseguire il lavoro come lavoro in background, passing the credentials you want into the -Credential parameter.

Vedi here, here & in msdn per more information

4

Ho appena trascorso il giorno di fissaggio questo per me stesso.

ho finalmente stato in grado di farlo funzionare con l'aggiunta di -Scope Processo a Set-ExecutionPolicy

invoker.Invoke("Set-ExecutionPolicy Unrestricted -Scope Process"); 
+0

grazie, questo ha risolto il mio problema dopo aver visto che dovevo usare "Set-ExecutionPolicy Unrestricted" su un centinaio di siti, il processo -Scope lo ha fatto per me! – Thousand

Problemi correlati