So rufen Sie eine Powershell-Skriptdatei (example.ps1) in C # auf

Ich habe versucht, ein Skript localwindows.ps1 in C # mit folgendem Code auszuführen:

               PSCredential credential = new PSCredential(userName, securePassword);
                WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "machineName", 5985, "/wsman", shellUri, credential);
                using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
                {

                    runspace.Open();
                    String file = "C:\\localwindows.ps1";
                    Pipeline pipeline = runspace.CreatePipeline();
                    pipeline.Commands.AddScript(file);
                    pipeline.Commands.Add("Out-String");
                    Collection<PSObject> results = pipeline.Invoke();
                }

Ausnahme: 'Der Begriff' C: \ localwindows.ps1 'wird nicht als Name eines Cmdlets, einer Funktion, einer Skriptdatei oder eines ausführbaren Programms erkannt.

Also habe ich folgendes versucht:

PSCredential credential = new PSCredential(userName, securePassword);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "machineName", 5985, "/wsman", shellUri, credential);
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{

    runspace.Open();

    using (PowerShell powershell = PowerShell.Create())
    {
        powershell.Runspace = runspace;           

        PSCommand new1 = new PSCommand();
        String machinename = "machinename";
        String file = "C:\\localwindows.ps1";
        new1.AddCommand("Invoke-Command");
        new1.AddParameter("computername", machinename);
        new1.AddParameter("filepath", file);         


        powershell.Commands = new1;
        Console.WriteLine(powershell.Commands.ToString());
        Collection<PSObject> results = powershell.Invoke();

     }

Ich erhalte die Fehlermeldung: "Pfad 'C: \ localwindows.ps1' kann nicht gefunden werden, da er nicht vorhanden ist."

Mit dem Befehl 'Invoke-Command -ComputerName "machineName" -Dateipfad C: \ localwindows.ps1' von Powershell auf dem lokalen Computer wurde jedoch ein neues Konto auf dem Remote-Computer erstellt.

Wie rufe ich das Skript localwindows.ps1 in C # auf? Wie führe ich den Befehl 'Invoke-Command -ComputerName "machineName" -Dateipfad C: \ localwindows.ps1' über C # aus?

Das Skript localwindows.ps1 lautet

$comp = [adsi]“WinNT://machinename,computer”
$user = $comp.Create(“User”, "account3")
$user.SetPassword(“change,password.10")
$user.SetInfo()

Antworten auf die Frage(2)

Ihre Antwort auf die Frage