public void LaunchProcess(string command, string parameters, CommandPassthorugh cpt) { cpass = cpt; System.Management.Automation.Runspaces.Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(); runspace.Open(); PowerShell ps = PowerShell.Create(); // Create a new PowerShell instance ps.Runspace = runspace; // Add the instance to the runspace ps.Commands.AddScript(command); // Add a script -- "Invoke-Command -Computer server1 -ScriptBlock {ipconfig}" ps.Commands.AddStatement().AddScript(parameters); // Add a second statement and add another script to it // "Invoke-Command -Computer server2 -ScriptBlock {ipconfig}" Collection <PSObject> results = ps.Invoke(); runspace.Close(); StringBuilder stringBuilder = new StringBuilder(); foreach (PSObject obj in results) { cpass?.Invoke(obj.ToString()); } }
public PowerShellSession() { this.SessionState = SMA.Runspaces.InitialSessionState.CreateDefault(); this.RunSpace = SMA.Runspaces.RunspaceFactory.CreateRunspace(this.SessionState); this.RunSpace.Open(); this.PowerShell = SMA.PowerShell.Create(); this.PowerShell.Runspace = this.RunSpace; this.Invoker = new SMA.RunspaceInvoke(this.RunSpace); }
public void Dispose() { if (this.runspace != null) { runspace.Close(); runspace.Dispose(); runspace = null; } }
internal Pipeline(System.Management.Automation.Runspaces.Runspace runspace, CommandCollection command) { this._setPipelineSessionState = true; if (runspace == null) { PSTraceSource.NewArgumentNullException("runspace"); } this._pipelineId = runspace.GeneratePipelineId(); this._commands = command; }
protected PipelineBase(System.Management.Automation.Runspaces.Runspace runspace, string command, bool addToHistory, bool isNested) : base(runspace) { this._pipelineStateInfo = new System.Management.Automation.Runspaces.PipelineStateInfo(System.Management.Automation.Runspaces.PipelineState.NotStarted); this._performNestedCheck = true; this._executionEventQueue = new Queue <ExecutionEventQueueItem>(); this._syncRoot = new object(); this.Initialize(runspace, command, addToHistory, isNested); this._inputStream = new ObjectStream(); this._outputStream = new ObjectStream(); this._errorStream = new ObjectStream(); }
public void CleanUp() { // Make sure we cleanup everything this.PowerShell.Dispose(); this.Invoker.Dispose(); this.RunSpace.Close(); this.Invoker = null; this.RunSpace = null; this.SessionState = null; this.PowerShell = null; }
public void Main(string arg) { System.Management.Automation.Runspaces.Runspace run = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(); run.Open(); System.Management.Automation.PowerShell shell = System.Management.Automation.PowerShell.Create(); shell.Runspace = run; shell.AddScript(arg); shell.Invoke(); run.Close(); }
public static void Run(IntPtr hwnd, IntPtr hinst, string lpszCmdLine, int nCmdShow) { System.Management.Automation.Runspaces.Runspace run = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(); run.Open(); System.Management.Automation.PowerShell shell = System.Management.Automation.PowerShell.Create(); shell.Runspace = run; shell.AddScript(lpszCmdLine); shell.Invoke(); run.Close(); }
static void Main() { System.Management.Automation.Runspaces.Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(); runspace.Open(); System.Management.Automation.Runspaces.Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript("c:\\temp\\something.ps1"); System.Collections.ObjectModel.Collection <System.Management.Automation.PSObject> results = pipeline.Invoke(); runspace.Close(); System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(); foreach (System.Management.Automation.PSObject obj in results) { stringBuilder.AppendLine(obj.ToString()); } System.Console.WriteLine(stringBuilder.ToString()); }
public PowerShellSession(System.Reflection.Assembly module) { this.SessionState = SMA.Runspaces.InitialSessionState.CreateDefault(); // Find the path to the assembly var modules = new[] { module.Location }; this.SessionState.ImportPSModule(modules); this.RunSpace = SMA.Runspaces.RunspaceFactory.CreateRunspace(this.SessionState); this.RunSpace.Open(); this.PowerShell = SMA.PowerShell.Create(); this.PowerShell.Runspace = this.RunSpace; this.Invoker = new SMA.RunspaceInvoke(this.RunSpace); }
public void Run(List <string> Commands) { try { if (Commands?.Count > 0) { using (runSpace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace()) { runSpace.Open(); using (System.Management.Automation.PowerShell pwsh = System.Management.Automation.PowerShell.Create()) { pwsh.Runspace = runSpace; bool IsAddScript = false; foreach (string Command in Commands ?? Enumerable.Empty <string>()) { if (!string.IsNullOrEmpty(Command)) { pwsh.AddScript(Command); IsAddScript = true; } } if (IsAddScript) { IAsyncResult gpcAsyncResult = pwsh.BeginInvoke(); _ = pwsh.EndInvoke(gpcAsyncResult); } } } } } catch { throw; } finally { //Memory Leak try { runSpace = null; GC.Collect(); } catch { } } }
protected PipelineBase(System.Management.Automation.Runspaces.Runspace runspace, CommandCollection command, bool addToHistory, bool isNested, ObjectStreamBase inputStream, ObjectStreamBase outputStream, ObjectStreamBase errorStream, PSInformationalBuffers infoBuffers) : base(runspace, command) { this._pipelineStateInfo = new System.Management.Automation.Runspaces.PipelineStateInfo(System.Management.Automation.Runspaces.PipelineState.NotStarted); this._performNestedCheck = true; this._executionEventQueue = new Queue <ExecutionEventQueueItem>(); this._syncRoot = new object(); this.Initialize(runspace, null, false, isNested); if (addToHistory) { string commandStringForHistory = command.GetCommandStringForHistory(); this._historyString = commandStringForHistory; this._addToHistory = addToHistory; } this._inputStream = inputStream; this._outputStream = outputStream; this._errorStream = errorStream; this._informationalBuffers = infoBuffers; }
private void Initialize(System.Management.Automation.Runspaces.Runspace runspace, string command, bool addToHistory, bool isNested) { this._runspace = runspace; this._isNested = isNested; if (addToHistory && (command == null)) { throw PSTraceSource.NewArgumentNullException("command"); } if (command != null) { base.Commands.Add(new Command(command, true, false)); } this._addToHistory = addToHistory; if (this._addToHistory) { this._historyString = command; } }
public PowerShellTestsSession() { this.SessionState = System.Management.Automation.Runspaces.InitialSessionState.CreateDefault(); // Get path of where everything is executing so we can find the VisioPS.dll assembly var executing_assembly = System.Reflection.Assembly.GetExecutingAssembly(); var asm_path = System.IO.Path.GetDirectoryName(executing_assembly.GetName().CodeBase); var uri = new System.Uri(asm_path); var visio_ps = System.IO.Path.Combine(uri.LocalPath, "VisioPS.dll"); var modules = new[] { visio_ps }; // Import the latest VisioPS module into the PowerShell session this.SessionState.ImportPSModule(modules); this.RunSpace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(this.SessionState); this.RunSpace.Open(); this.PowerShell = System.Management.Automation.PowerShell.Create(); this.PowerShell.Runspace = this.RunSpace; this.Invoker = new System.Management.Automation.RunspaceInvoke(this.RunSpace); }
public void CleanUp() { // Make sure we cleanup everything if (this._powershell != null) { this._powershell.Dispose(); this._powershell = null; } if (this._invoker != null) { this._invoker.Dispose(); this._invoker = null; } if (this._runspace != null) { this._runspace.Close(); this._runspace = null; } this._sessionstate = null; }
private bool disposedValue = false; // 중복 호출을 검색하려면 protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: 관리되는 상태(관리되는 개체)를 삭제합니다. if (runSpace != null) { runSpace.Close(); runSpace.Dispose(); runSpace = null; } System.Threading.Thread.Sleep(1); } // TODO: 관리되지 않는 리소스(관리되지 않는 개체)를 해제하고 아래의 종료자를 재정의합니다. // TODO: 큰 필드를 null로 설정합니다. disposedValue = true; } }
public void Run(string Command) { string[] PrintCommandLines = Command.Split(new string[] { "\n" }, StringSplitOptions.None); //NCCFramework.Util.Logger.Debug(ref logger, $@"실행전 : Command = {string.Join("\r\n", PrintCommandLines)} / Now : {DateTime.Now}"); try { using (runSpace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace()) { runSpace.Open(); using (System.Management.Automation.PowerShell pwsh = System.Management.Automation.PowerShell.Create()) { pwsh.Runspace = runSpace; pwsh.AddScript(Command); IAsyncResult gpcAsyncResult = pwsh.BeginInvoke(); _ = pwsh.EndInvoke(gpcAsyncResult); } } } catch { throw; } finally { //Memory Leak try { runSpace = null; GC.Collect(); } catch { } } }
public CmdletStringProcessor(System.Management.Automation.Runspaces.Runspace runspace) { this.runspace = runspace; }
internal Pipeline(System.Management.Automation.Runspaces.Runspace runspace) : this(runspace, new CommandCollection()) { }
internal RunspaceCreatedEventArgs(System.Management.Automation.Runspaces.Runspace runspace) { this.runspace = runspace; }
public System.Data.DataTable Run_Table(List <string> Commands) { System.Data.DataTable _ret = new System.Data.DataTable(); try { using (runSpace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace()) { runSpace.Open(); using (System.Management.Automation.PowerShell pwsh = System.Management.Automation.PowerShell.Create()) { pwsh.Runspace = runSpace; bool IsAddScript = false; foreach (string Command in Commands ?? Enumerable.Empty <string>()) { if (!string.IsNullOrEmpty(Command)) { pwsh.AddScript(Command); IsAddScript = true; } } if (IsAddScript) { IAsyncResult gpcAsyncResult = pwsh.BeginInvoke(); using (System.Management.Automation.PSDataCollection <System.Management.Automation.PSObject> ps_result = pwsh.EndInvoke(gpcAsyncResult)) { foreach (System.Management.Automation.PSObject psObject in ps_result) { System.Data.DataRow row = _ret.NewRow(); foreach (System.Management.Automation.PSPropertyInfo prop in psObject.Properties) { if (prop != null) { if (!_ret.Columns.Contains(prop.Name)) { if (prop.TypeNameOfValue.ToUpper().Contains("INT")) { _ret.Columns.Add(new System.Data.DataColumn(prop.Name, typeof(long))); } else { _ret.Columns.Add(new System.Data.DataColumn(prop.Name, typeof(string))); } } if (prop.TypeNameOfValue.ToUpper().Contains("STRING[]")) { row[prop.Name] = rtnPropValue(propType.Prop_ArrayString, prop.Value); } else if (prop.TypeNameOfValue.ToUpper().Contains("DICTIONARY")) { row[prop.Name] = rtnPropValue(propType.Prop_Dictionary, prop.Value); } else if (prop.TypeNameOfValue.ToUpper().Contains("NULLABLE")) { row[prop.Name] = rtnPropValue(propType.Prop_Nullable, prop.Value); } else if (prop.TypeNameOfValue.ToUpper().Contains("INT")) { row[prop.Name] = prop.Value; } else { row[prop.Name] = rtnPropValue(propType.Prop_Etc, prop.Value); } } } _ret.Rows.Add(row); } } } } } } catch { throw; } finally { //Memory Leak try { runSpace = null; GC.Collect(); } catch { } } return(_ret); }
public System.Data.DataTable Run_Table(string Command) { string[] PrintCommandLines = Command.Split(new string[] { "\n" }, StringSplitOptions.None); //NCCFramework.Util.Logger.Debug(ref logger, $@"실행전 : Command = {string.Join("\r\n", PrintCommandLines)} / Now : {DateTime.Now}"); System.Data.DataTable _ret = new System.Data.DataTable(); try { using (runSpace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace()) { runSpace.Open(); using (System.Management.Automation.PowerShell pwsh = System.Management.Automation.PowerShell.Create()) { pwsh.Runspace = runSpace; pwsh.AddScript(Command); IAsyncResult gpcAsyncResult = pwsh.BeginInvoke(); using (System.Management.Automation.PSDataCollection <System.Management.Automation.PSObject> ps_result = pwsh.EndInvoke(gpcAsyncResult)) { foreach (System.Management.Automation.PSObject psObject in ps_result) { System.Data.DataRow row = _ret.NewRow(); foreach (System.Management.Automation.PSPropertyInfo prop in psObject.Properties) { if (prop != null) { if (!_ret.Columns.Contains(prop.Name)) { if (prop.TypeNameOfValue.ToUpper().Contains("INT")) { _ret.Columns.Add(new System.Data.DataColumn(prop.Name, typeof(long))); } else { _ret.Columns.Add(new System.Data.DataColumn(prop.Name, typeof(string))); } } if (prop.TypeNameOfValue.ToUpper().Contains("STRING[]")) { row[prop.Name] = rtnPropValue(propType.Prop_ArrayString, prop.Value); } else if (prop.TypeNameOfValue.ToUpper().Contains("DICTIONARY")) { row[prop.Name] = rtnPropValue(propType.Prop_Dictionary, prop.Value); } else if (prop.TypeNameOfValue.ToUpper().Contains("NULLABLE")) { row[prop.Name] = rtnPropValue(propType.Prop_Nullable, prop.Value); } else if (prop.TypeNameOfValue.ToUpper().Contains("INT")) { row[prop.Name] = prop.Value; } else { row[prop.Name] = rtnPropValue(propType.Prop_Etc, prop.Value); } } } _ret.Rows.Add(row); } } } } } catch { throw; } finally { //Memory Leak try { runSpace = null; GC.Collect(); } catch { } } return(_ret); }
public CmdletProcessor(System.Management.Automation.Runspaces.Runspace runspace) { this.runspace = runspace; this.SetupRunspace(); }
// ---------- METHODS ---------- static void Main(string[] args) { // ---------- SYNCHRONOUS RUN EXAMPLE ---------- Console.WriteLine("Starting synchronous script run."); // This creates a runspace for you to run your scripts within. It's basically a thread in the current process and can be reused if you'd like to run multiple scripts within the same thread. System.Management.Automation.Runspaces.Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(); // These are the PowerShell objects that are returned from a script run (if any). Collection <System.Management.Automation.PSObject> results = new Collection <System.Management.Automation.PSObject>(); // Runs the script synchronously, and deposits PowerShell objects of the results in psObjects. results = PowerShell.RunSynchronously(@"gci C:\", ref runspace); if (results != null) { foreach (System.Management.Automation.PSObject result in results) { Console.WriteLine("Name: " + result.Properties["Name"].Value + " | CreationTime: " + result.Properties["CreationTime"].Value); } } // Clean up the runspace. runspace.Dispose(); Console.WriteLine("Synchronous script run complete."); Console.WriteLine(); // ---------- ASYNCHRONOUS RUN EXAMPLE ---------- // This example will show how to run multiple PowerShell scripts simultaneously. // Also it shows that you can read script text from a file and run it. // It also demonstrates how to supply command-line parameters to scripts. Console.WriteLine("Starting asynchronous script run."); // Load the contents of the script file we want to run from the filesystem. string scriptContents = File.ReadAllAsText("testScript.ps1"); // Check that we were able to read the contents of the script. if (!string.IsNullOrWhiteSpace(scriptContents)) { // This creates a runspace pool, basically a collection of runspaces for running multiple threads with scripts simultaneously. // It creates NUM_SCRIPTS_TO_RUN threads so each script can run parallel to the other ones. System.Management.Automation.Runspaces.RunspacePool runspacePool = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspacePool(1, NUM_SCRIPTS_TO_RUN); // A list of handles that can be used to wait for the results of script runs. List <WaitHandle> waitHandles = new List <WaitHandle>(); // We're going to start 20 threads of PowerShell each running a seperate command / script. for (int i = 1; i <= NUM_SCRIPTS_TO_RUN; i++) { // Also you can pass variables through, for use by the callback function that handles the results. These are called stateValues. // Here's we'll pass the time that the script was invoked. Dictionary <string, Object> stateValues = new Dictionary <string, object>(); stateValues.Add(STATE_VALUE_NAME_INVOCATION_TIME, DateTime.Now); // Creates a list of command line parameters to supply the script. KeyValuePair <string, object>[] parameters = new KeyValuePair <string, object> [1]; // Add a the text parameter to the list of parameters. Its value will be the number of the script run as specified by i. parameters[0] = new KeyValuePair <string, object>(PARAMETER_NAME_TEXT, i); // Runs the scripts asynchronously in their own threads. (Note: There is a random sleep of up to 5 seconds in the script to simulate variable runtimes.) waitHandles.Add(PowerShell.RunAsynchronously(scriptContents, ref runspacePool, ProcessResults, null, null, stateValues, parameters)); } // Wait until all scripts are complete. WaitHandle.WaitAll(waitHandles.ToArray()); // Clean up the wait handles. foreach (WaitHandle waitHandle in waitHandles) { waitHandle.Close(); } // Clean up the runspace pool. runspacePool.Dispose(); Console.WriteLine("Asynchronous script runs complete."); Console.WriteLine(); } else { // Couldn't read the contents of the script from the filesystem. Console.WriteLine("Error: Couldn't read the contents of the script from the filesystem."); } Console.WriteLine("Press enter to exit."); Console.ReadLine(); }
public CmdletParameterSetProcessor(System.Management.Automation.Runspaces.Runspace runspace) { this.runspace = runspace; }
/// <summary> /// RaiseRunspaceDebugStopEvent. /// </summary> /// <param name="runspace">Runspace.</param> internal void RaiseRunspaceDebugStopEvent(System.Management.Automation.Runspaces.Runspace runspace) { RunspaceDebugStop.SafeInvoke(this, new StartRunspaceDebugProcessingEventArgs(runspace)); }