Aby wywołać plik skryptu powershell (example.ps1) z C #
Próbowałem uruchomić skrypt localwindows.ps1 z C #, używając następującego kodu:
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();
}
Ale otrzymanie wyjątku: „Termin„ C: localwindows.ps1 ”nie jest rozpoznawany jako nazwa polecenia cmdlet, funkcji, pliku skryptu lub programu operacyjnego.
Próbowałem więc:
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();
}
Dostaję błąd: „Nie można znaleźć ścieżki„ C: localwindows.ps1 ”, ponieważ nie istnieje.”
Ale za pomocą polecenia „Invoke-Command -ComputerName” nazwa_komputera „-filepath C: localwindows.ps1” z powershell na komputerze lokalnym utworzono nowe konto na komputerze zdalnym.
Jak wywołać skrypt localwindows.ps1 z C #? Jak wykonać polecenie 'Invoke-Command -ComputerName "machineName" -filepath C: localwindows.ps1' do C #?
Skrypt localwindows.ps1 jest
$comp = [adsi]“WinNT://machinename,computer”
$user = $comp.Create(“User”, "account3")
$user.SetPassword(“change,password.10")
$user.SetInfo()