Comment faire pour exécuter des scripts PowerShell à partir de C#

Je suis en train d'exécuter un script PowerShell avec le C#, mais je n'ai pas de succès. Voici ma fonction:

private void ExecutePowerShellCommand(string scriptfile)
{
    RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

    Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
    runspace.Open();

    RunspaceInvoke scriptInvoker = new RunspaceInvoke();
    scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

    Pipeline pipeline = runspace.CreatePipeline();

    //Here's how you add a new script with arguments
    Command myCommand = new Command(scriptfile);
    //CommandParameter testParam = new CommandParameter("key", "value");
    //myCommand.Parameters.Add(testParam);

    pipeline.Commands.Add(myCommand);

    //Execute PowerShell script
    pipeline.Invoke();
}

C'est l'erreur que je reçois:

L'accès à la clé de registre " HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell " est refusé.

Comment puis-je résoudre ce problème? J'ai vu des idées pour usurpation d'identité, mais je n'ai pas l'air de trouver tout de bons exemples à imiter. Je voudrais lancer ce script en tant qu'administrateur.

J'ai fait les déclarations suivantes:

[DllImport("advapi32.dll")]
private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr handle);

public delegate void IncognitoDelegate(params object[] args);

J'ai créé la fonction suivante pour usurpation d'identité:

public static void Impersonate(IncognitoDelegate incognitoDelegate, params object[] args)
{
    System.IntPtr token = new IntPtr();
    WindowsIdentity wi;
    if (LogonUser("myusername", "", "mypassword", 8, 0, ref token))
    {
        wi = new WindowsIdentity(token);
        WindowsImpersonationContext wic = wi.Impersonate();

        incognitoDelegate(args);

        wic.Undo();
    }
    CloseHandle(token);
}

J'ai créé une fonction qui est utilisée en tant que délégué:

private static void GIncognito(params object[] args)
{
    RunspaceInvoke scriptInvoker = new RunspaceInvoke();
    scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
}

Et j'ai modifié ma méthode:

private void ExecutePowerShellCommand(string scriptfile)
{
    RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

    Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
    runspace.Open();

    Impersonate(new Util.IncognitoDelegate(GIncognito));
    //RunspaceInvoke scriptInvoker = new RunspaceInvoke();
    //scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

    Pipeline pipeline = runspace.CreatePipeline();

    //Here's how you add a new script with arguments
    Command myCommand = new Command(scriptfile);
    //CommandParameter testParam = new CommandParameter("key", "value");
    //myCommand.Parameters.Add(testParam);

    pipeline.Commands.Add(myCommand);

    //Execute PowerShell script
    pipeline.Invoke();
}

Le résultat a été...

... le très sam erreur, me disant que je ne peux pas accéder à des clés de registre.

re: ne peut pas accéder à des clés de registre, Vous allez avoir à utiliser un compte qui peut modifier des clés de registre ou de l'utilisation d'une technique qui ne impliquent une modification de la politique d'exécution à l'intérieur de l'exécution de powershell instance.
l'usurpation d'identité est beaucoup trop pour cela... tout ce que vous devez faire est de changer le champ d'application que le Set-ExecutionPolicy utilise... voir ma réponse ci-dessous.

OriginalL'auteur Lajos Arpad | 2012-11-20