internal ClientRemotePowerShell( PowerShell shell, ObjectStreamBase inputstream, ObjectStreamBase outputstream, ObjectStreamBase errorstream, PSInformationalBuffers informationalBuffers, PSInvocationSettings settings, RemoteRunspacePoolInternal runspacePool) { using (ClientRemotePowerShell.tracer.TraceConstructor((object)this)) { this.shell = shell; this.informationalBuffers = informationalBuffers; this.InputStream = inputstream; this.errorstream = errorstream; this.outputstream = outputstream; this.settings = settings; this.clientRunspacePoolId = runspacePool.InstanceId; this.hostToUse = settings == null || settings.Host == null ? runspacePool.Host : settings.Host; this.computerName = runspacePool.ConnectionInfo.ComputerName; this.dataStructureHandler = runspacePool.DataStructureHandler.CreatePowerShellDataStructureHandler(this); this.dataStructureHandler.InvocationStateInfoReceived += new EventHandler <RemoteDataEventArgs <PSInvocationStateInfo> >(this.HandleInvocationStateInfoReceived); this.dataStructureHandler.OutputReceived += new EventHandler <RemoteDataEventArgs <object> >(this.HandleOutputReceived); this.dataStructureHandler.ErrorReceived += new EventHandler <RemoteDataEventArgs <ErrorRecord> >(this.HandleErrorReceived); this.dataStructureHandler.InformationalMessageReceived += new EventHandler <RemoteDataEventArgs <InformationalMessage> >(this.HandleInformationalMessageReceived); this.dataStructureHandler.HostCallReceived += new EventHandler <RemoteDataEventArgs <RemoteHostCall> >(this.HandleHostCallReceived); this.dataStructureHandler.ClosedNotificationFromRunspacePool += new EventHandler <RemoteDataEventArgs <Exception> >(this.HandleCloseNotificationFromRunspacePool); this.dataStructureHandler.BrokenNotificationFromRunspacePool += new EventHandler <RemoteDataEventArgs <Exception> >(this.HandleBrokenNotificationFromRunspacePool); } }
void IInvokeInteractive.Run() { InitialisePowerShellImpl(); ShouldExit = false; // Set up the control-C handler. var treatAsInputOld = Console.TreatControlCAsInput; Console.CancelKeyPress += HandleControlC; Console.TreatControlCAsInput = false; try { // Read commands and run them until the ShouldExit flag is set by // the user calling "exit". var invocationSettings = new PSInvocationSettings { AddToHistory = true }; while (!ShouldExit) { var prompt = GetPrompt(); _consoleHost.UI.Write(_consoleHost.UI.RawUI.ForegroundColor, _consoleHost.UI.RawUI.BackgroundColor, prompt); var cmd = ReadLine() ?? _consoleReadLine.Read(); InvokeScript(cmd, invocationSettings); } } finally { Console.CancelKeyPress -= HandleControlC; Console.TreatControlCAsInput = treatAsInputOld; } // Exit with the desired exit code that was set by the exit command. // The exit code is set in the host by the MyHost.SetShouldExit() method. }
public static PSInvocationSettings GetPSInvocationSettings() { PSInvocationSettings pSInvocationSetting = new PSInvocationSettings(); pSInvocationSetting.FlowImpersonationPolicy = true; return(pSInvocationSetting); }
internal void Initialize(ObjectStreamBase inputstream, ObjectStreamBase outputstream, ObjectStreamBase errorstream, PSInformationalBuffers informationalBuffers, PSInvocationSettings settings) { this.initialized = true; this.informationalBuffers = informationalBuffers; this.InputStream = inputstream; this.errorstream = errorstream; this.outputstream = outputstream; this.settings = settings; if ((settings == null) || (settings.Host == null)) { this.hostToUse = this.runspacePool.Host; } else { this.hostToUse = settings.Host; } this.dataStructureHandler = this.runspacePool.DataStructureHandler.CreatePowerShellDataStructureHandler(this); this.dataStructureHandler.InvocationStateInfoReceived += new EventHandler <RemoteDataEventArgs <PSInvocationStateInfo> >(this.HandleInvocationStateInfoReceived); this.dataStructureHandler.OutputReceived += new EventHandler <RemoteDataEventArgs <object> >(this.HandleOutputReceived); this.dataStructureHandler.ErrorReceived += new EventHandler <RemoteDataEventArgs <ErrorRecord> >(this.HandleErrorReceived); this.dataStructureHandler.InformationalMessageReceived += new EventHandler <RemoteDataEventArgs <InformationalMessage> >(this.HandleInformationalMessageReceived); this.dataStructureHandler.HostCallReceived += new EventHandler <RemoteDataEventArgs <RemoteHostCall> >(this.HandleHostCallReceived); this.dataStructureHandler.ClosedNotificationFromRunspacePool += new EventHandler <RemoteDataEventArgs <Exception> >(this.HandleCloseNotificationFromRunspacePool); this.dataStructureHandler.BrokenNotificationFromRunspacePool += new EventHandler <RemoteDataEventArgs <Exception> >(this.HandleBrokenNotificationFromRunspacePool); this.dataStructureHandler.ConnectCompleted += new EventHandler <RemoteDataEventArgs <Exception> >(this.HandleConnectCompleted); this.dataStructureHandler.ReconnectCompleted += new EventHandler <RemoteDataEventArgs <Exception> >(this.HandleConnectCompleted); this.dataStructureHandler.RobustConnectionNotification += new EventHandler <ConnectionStatusEventArgs>(this.HandleRobustConnectionNotification); this.dataStructureHandler.CloseCompleted += new EventHandler <EventArgs>(this.HandleCloseCompleted); }
protected void InvokeScript(string script, PSInvocationSettings invocationSettings) { _pipelineDoneEvent.Reset(); var pipeTask = Task.Factory.StartNew(() => Execute(script, invocationSettings)); pipeTask.ContinueWith(t => { _pipelineDoneEvent.Set(); }, TaskContinuationOptions.ExecuteSynchronously); _methodCallDispatcher.DispatchMethodCalls(_pipelineDoneEvent); pipeTask.Wait(); }
public static void InvokeAndClear(this PowerShell pwsh, PSInvocationSettings invocationSettings = null) { try { pwsh.Invoke(input: null, invocationSettings); } finally { pwsh.Commands.Clear(); } }
/// <summary> /// Basic script execution routine. Any runtime exceptions are /// caught and passed back to the Windows PowerShell engine to /// display. /// </summary> /// <param name="cmd">Script to run.</param> /// <param name="invocationSettings"></param> protected void Execute(string cmd, PSInvocationSettings invocationSettings = null) { try { // Run the command with no input. ExecuteHelper(cmd, null, invocationSettings); } catch (RuntimeException rte) { ReportException(rte); } }
public void Invoke(string command) { if (!IsRunspaceOpen()) { InitializePowerShell(); } var settings = new PSInvocationSettings() { AddToHistory = true }; InvokeScript(command, settings); }
/// <summary> /// A helper class that builds and executes a pipeline that writes /// to the default output path. Any exceptions that are thrown are /// just passed to the caller. Since all output goes to the default /// outter, this method does not return anything. /// </summary> /// <param name="cmd">The script to run.</param> /// <param name="input"> /// Any input arguments to pass to the script. /// If null then nothing is passed in. /// </param> /// <param name="invocationSettings"></param> private void ExecuteHelper(string cmd, object input, PSInvocationSettings invocationSettings = null) { // Ignore empty command lines. if (string.IsNullOrEmpty(cmd)) { return; } // Create the pipeline object and make it available to the // ctrl-C handle through the currentPowerShell instance // variable. lock (_instanceLock) { _currentPowerShell = PowerShell.Create(); } // Add a script and command to the pipeline and then run the pipeline. Place // the results in the currentPowerShell variable so that the pipeline can be // stopped. try { _currentPowerShell.Runspace = _runspace; _currentPowerShell.AddScript(cmd); // Add the default outputter to the end of the pipe and then call the // MergeMyResults method to merge the output and error streams from the // pipeline. This will result in the output being written using the PSHost // and PSHostUserInterface classes instead of returning objects to the host // application. _currentPowerShell.AddCommand("out-default"); _currentPowerShell.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); // If there is any input pass it in, otherwise just invoke the // the pipeline. _currentPowerShell.Invoke(input != null ? new[] { input } : new PSObject[] {}, invocationSettings); } finally { // Dispose the PowerShell object and set currentPowerShell to null. // It is locked because currentPowerShell may be accessed by the // ctrl-C handler. lock (_instanceLock) { _currentPowerShell.Dispose(); _currentPowerShell = null; } } }
/// <summary> /// Initialize the client remote powershell instance. /// </summary> /// <param name="inputstream">Input for execution.</param> /// <param name="errorstream">error stream to which /// data needs to be written to</param> /// <param name="informationalBuffers">informational buffers /// which will hold debug, verbose and warning messages</param> /// <param name="settings">settings based on which this powershell /// needs to be executed</param> /// <param name="outputstream">output stream to which data /// needs to be written to</param> internal void Initialize( ObjectStreamBase inputstream, ObjectStreamBase outputstream, ObjectStreamBase errorstream, PSInformationalBuffers informationalBuffers, PSInvocationSettings settings) { initialized = true; this.informationalBuffers = informationalBuffers; InputStream = inputstream; this.errorstream = errorstream; this.outputstream = outputstream; this.settings = settings; if (settings is null || settings.Host is null) { hostToUse = runspacePool.Host; }
public static List <PSObject> RunCommand(Action <PowerShell> prepareAction, PsCommandContext context = null) { var ps = PowerShell.Create(); ps.Runspace = runspace; prepareAction(ps); var ret = new List <PSObject>(); var settings = new PSInvocationSettings { Host = new TestPsHost(context ?? new PsCommandContext()) }; foreach (var result in ps.Invoke(new Object[0], settings)) { Trace.WriteLine(result); ret.Add(result); } return(ret); }
/// <summary> /// Initialize the client remote powershell instance. /// </summary> /// <param name="inputstream">Input for execution.</param> /// <param name="errorstream">error stream to which /// data needs to be written to</param> /// <param name="informationalBuffers">informational buffers /// which will hold debug, verbose and warning messages</param> /// <param name="settings">settings based on which this powershell /// needs to be executed</param> /// <param name="outputstream">output stream to which data /// needs to be written to</param> internal void Initialize( ObjectStreamBase inputstream, ObjectStreamBase outputstream, ObjectStreamBase errorstream, PSInformationalBuffers informationalBuffers, PSInvocationSettings settings) { initialized = true; this.informationalBuffers = informationalBuffers; InputStream = inputstream; this.errorstream = errorstream; this.outputstream = outputstream; this.settings = settings; if (settings == null || settings.Host == null) { hostToUse = runspacePool.Host; } else { hostToUse = settings.Host; } dataStructureHandler = runspacePool.DataStructureHandler.CreatePowerShellDataStructureHandler(this); // register for events from the data structure handler dataStructureHandler.InvocationStateInfoReceived += HandleInvocationStateInfoReceived; dataStructureHandler.OutputReceived += HandleOutputReceived; dataStructureHandler.ErrorReceived += HandleErrorReceived; dataStructureHandler.InformationalMessageReceived += HandleInformationalMessageReceived; dataStructureHandler.HostCallReceived += HandleHostCallReceived; dataStructureHandler.ClosedNotificationFromRunspacePool += HandleCloseNotificationFromRunspacePool; dataStructureHandler.BrokenNotificationFromRunspacePool += HandleBrokenNotificationFromRunspacePool; dataStructureHandler.ConnectCompleted += HandleConnectCompleted; dataStructureHandler.ReconnectCompleted += HandleConnectCompleted; dataStructureHandler.RobustConnectionNotification += HandleRobustConnectionNotification; dataStructureHandler.CloseCompleted += HandleCloseCompleted; }
public void Apply(IContextManager contextManager, IUpgradeLog logger) { // IDEA: The other alternative to a custom host is simply define function Write-Host var host = new ScriptHost(logger); var outputLogger = new OutputLogger(logger); var parameters = GetScriptParameterNames().ToList(); using (var runspace = RunspaceFactory.CreateRunspace(host)) { runspace.Open(); //runspace.SessionStateProxy.SetVariable("ErrorActionPreference", "Stop"); runspace.SessionStateProxy.SetVariable("SPContext", contextManager.CurrentContext); runspace.SessionStateProxy.SetVariable("SPUrl", contextManager.CurrentContext.Url); runspace.SessionStateProxy.SetVariable("SPUserName", contextManager.UserName); runspace.SessionStateProxy.SetVariable("SPPassword", contextManager.Password); runspace.SessionStateProxy.SetVariable("SPSecurePassword", contextManager.SecurePassword); PSCredential psCredential = null; if (!string.IsNullOrWhiteSpace(contextManager.UserName) && contextManager.SecurePassword != null) { psCredential = new PSCredential(contextManager.UserName, contextManager.SecurePassword); } runspace.SessionStateProxy.SetVariable("SPCredentials", psCredential); runspace.SessionStateProxy.SetVariable("SPVariables", _variables); // TODO: Allow custom parameters to be passed through (from ScriptMigrationProvider) // TODO: Store calculated PSCredential with ScriptHost / ScriptHostUI, so it returns from PromptForCredential //var initial = InitialSessionState.Create(); //initial.ImportPSModule("OfficeDevPnP.PowerShell.Commands"); using (var pipeline = runspace.CreatePipeline("Set-ExecutionPolicy Unrestricted -Scope Process -Confirm:$false -Force")) { var output = pipeline.Invoke(); } using (var pipeline = runspace.CreatePipeline("Import-Module OfficeDevPnP.PowerShell.Commands")) { var output = pipeline.Invoke(); } using (var shell = PowerShell.Create()) { shell.Runspace = runspace; //shell.AddScript("Set-ExecutionPolicy Unrestricted -Scope CurrentUser;"); //shell.AddScript("Import-Module OfficeDevPnP.PowerShell.Commands"); shell.AddCommand(_filePath); if (parameters.Any(p => string.Equals(p, "Context", StringComparison.InvariantCultureIgnoreCase))) { shell.AddParameter("Context", contextManager.CurrentContext); } if (parameters.Any(p => string.Equals(p, "Url", StringComparison.InvariantCultureIgnoreCase))) { shell.AddParameter("Url", contextManager.CurrentContext.Url); } if (parameters.Any(p => string.Equals(p, "UserName", StringComparison.InvariantCultureIgnoreCase))) { shell.AddParameter("UserName", contextManager.UserName); } if (parameters.Any(p => string.Equals(p, "Password", StringComparison.InvariantCultureIgnoreCase))) { shell.AddParameter("Password", contextManager.Password); } if (parameters.Any(p => string.Equals(p, "SecurePassword", StringComparison.InvariantCultureIgnoreCase))) { shell.AddParameter("SecurePassword", contextManager.SecurePassword); } if (parameters.Any(p => string.Equals(p, "Credentials", StringComparison.InvariantCultureIgnoreCase))) { shell.AddParameter("Credentials", psCredential); } // Custom parameters foreach (var kvp in _variables) { if (parameters.Any(p => string.Equals(p, kvp.Key, StringComparison.InvariantCultureIgnoreCase))) { shell.AddParameter(kvp.Key, kvp.Value); } } // Exit codes not supported... need to check exit within script and convert to error //shell.AddScript("Write-Host \"EXIT: $LastExitCode\";"); PSDataCollection <PSObject> outputCollection = new PSDataCollection <PSObject>(); //outputCollection.DataAdded += OutputCollection_DataAdded; outputCollection.DataAdded += outputLogger.OutputCollection_DataAdded; shell.Streams.Debug.DataAdded += outputLogger.Debug_DataAdded; shell.Streams.Error.DataAdded += outputLogger.Error_DataAdded; shell.Streams.Progress.DataAdded += outputLogger.Progress_DataAdded; shell.Streams.Verbose.DataAdded += outputLogger.Verbose_DataAdded; shell.Streams.Warning.DataAdded += outputLogger.Warning_DataAdded; var settings = new PSInvocationSettings() { ErrorActionPreference = ActionPreference.Stop }; IAsyncResult result = shell.BeginInvoke <PSObject, PSObject>(null, outputCollection, settings, null, null); while (result.IsCompleted == false) { //Console.WriteLine("Waiting for pipeline to finish..."); Thread.Sleep(1000); // TODO: Add timeout (configured from ScriptMigrationProvider) } //Console.WriteLine("** Host. ShouldExit: {0}, ExitCode: {1}, HadErrors: {0}. State: {1}, Reason: {2}", // host.ShouldExit, host.ExitCode, shell.HadErrors, shell.InvocationStateInfo.State, shell.InvocationStateInfo.Reason); //Console.WriteLine("Output (after script run):"); //foreach (PSObject outputItem in outputCollection) //{ // //TODO: handle/process the output items if required // Console.WriteLine(outputItem.BaseObject.ToString()); //} if (host.ExitCode != 0) { logger.Error("Script exited with code: {0}", host.ExitCode); if (shell.HadErrors) { foreach (var error in shell.Streams.Error) { logger.Error("{0}", error); } } throw new ScriptException(string.Format("Script exited with code: {0}", host.ExitCode)); } if (shell.HadErrors) { if (shell.Streams.Error.Count > 0) { logger.Error("Script had non-terminating errors. Suppress errors to allow script to run. State: {0}", shell.InvocationStateInfo.State); foreach (var error in shell.Streams.Error) { logger.Error("{0}", error); } throw new ScriptException(string.Format("{0}. {1}", shell.InvocationStateInfo.State, shell.InvocationStateInfo.Reason)); } else { logger.Warning("Script had non-terminating errors that were suppressed (error stream was empty). State: {0}", shell.InvocationStateInfo.State); } } logger.Verbose("Script '{0}' complete", _filePath); } } }
/// <summary> /// Initialize the client remote powershell instance /// </summary> /// <param name="inputstream">input for execution</param> /// <param name="errorstream">error stream to which /// data needs to be written to</param> /// <param name="informationalBuffers">informational buffers /// which will hold debug, verbose and warning messages</param> /// <param name="settings">settings based on which this powershell /// needs to be executed</param> /// <param name="outputstream">output stream to which data /// needs to be written to</param> internal void Initialize( ObjectStreamBase inputstream, ObjectStreamBase outputstream, ObjectStreamBase errorstream, PSInformationalBuffers informationalBuffers, PSInvocationSettings settings) { initialized = true; this.informationalBuffers = informationalBuffers; InputStream = inputstream; this.errorstream = errorstream; this.outputstream = outputstream; this.settings = settings; if (settings == null || settings.Host == null) { hostToUse = runspacePool.Host; } else { hostToUse = settings.Host; } dataStructureHandler = runspacePool.DataStructureHandler.CreatePowerShellDataStructureHandler(this); // register for events from the data structure handler dataStructureHandler.InvocationStateInfoReceived += new EventHandler<RemoteDataEventArgs<PSInvocationStateInfo>>(HandleInvocationStateInfoReceived); dataStructureHandler.OutputReceived += new EventHandler<RemoteDataEventArgs<object>>(HandleOutputReceived); dataStructureHandler.ErrorReceived += new EventHandler<RemoteDataEventArgs<ErrorRecord>>(HandleErrorReceived); dataStructureHandler.InformationalMessageReceived += new EventHandler<RemoteDataEventArgs<InformationalMessage>>(HandleInformationalMessageReceived); dataStructureHandler.HostCallReceived += new EventHandler<RemoteDataEventArgs<RemoteHostCall>>(HandleHostCallReceived); dataStructureHandler.ClosedNotificationFromRunspacePool += new EventHandler<RemoteDataEventArgs<Exception>>(HandleCloseNotificationFromRunspacePool); dataStructureHandler.BrokenNotificationFromRunspacePool += new EventHandler<RemoteDataEventArgs<Exception>>(HandleBrokenNotificationFromRunspacePool); dataStructureHandler.ConnectCompleted += new EventHandler<RemoteDataEventArgs<Exception>>(HandleConnectCompleted); dataStructureHandler.ReconnectCompleted += new EventHandler<RemoteDataEventArgs<Exception>>(HandleConnectCompleted); dataStructureHandler.RobustConnectionNotification += new EventHandler<ConnectionStatusEventArgs>(HandleRobustConnectionNotification); dataStructureHandler.CloseCompleted += new EventHandler<EventArgs>(HandleCloseCompleted); }
public static Collection <TResult> InvokeAndClear <TResult>(this PowerShell pwsh, PSInvocationSettings invocationSettings = null) { try { return(pwsh.Invoke <TResult>(input: null, invocationSettings)); } finally { pwsh.Commands.Clear(); } }
public static Collection <TResult> InvokeCommand <TResult>(this PowerShell pwsh, PSCommand psCommand, PSInvocationSettings invocationSettings = null) { pwsh.Commands = psCommand; return(pwsh.InvokeAndClear <TResult>(invocationSettings)); }
public ClientMessage[] ExecuteCommand(string command) { ClientMessage[] clientMessages; if (command != null) { lock (this.clientRequestLock) { lock (this.sessionStateLock) { if (this.State == PowwaSession.SessionState.Available) { PSCommand commands = null; try { commands = ScriptBlock.Create(command).GetPowerShell(new object[0]).Commands; } catch (ScriptBlockToPowerShellNotSupportedException scriptBlockToPowerShellNotSupportedException) { } catch (RuntimeException runtimeException) { } if (commands == null) { commands = new PSCommand(); commands.AddScript(command); } commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); Command outputCmd = new Command("Out-Default", false, false); commands.AddCommand(outputCmd); this.executingCommandPowerShell.Commands = commands; this.executingCommandPowerShell.HistoryString = command; try { PSInvocationSettings pSInvocationSetting = new PSInvocationSettings(); pSInvocationSetting.AddToHistory = true; /*Exception ex; * this.State = PowwaSession.SessionState.ExecutingCommand; * this.exec.ExecuteCommandAsync(command, out ex, Microsoft.PowerShell.Executor.ExecutionOptions.AddOutputter | Microsoft.PowerShell.Executor.ExecutionOptions.AddToHistory); * if (ex != null) throw ex; */ this.executingCommandPowerShell.BeginInvoke <object>(null, pSInvocationSetting, null, null); } catch (Exception exception1) { Exception exception = exception1; this.WriteException(exception); if (exception as InvalidRunspaceStateException != null) { this.PostClientMessage(new SessionTerminatedMessage(), false); } } } else { PowwaEvents.PowwaEVENT_DEBUG_LOG1("ExecuteCommand(): Invalid Session State", "SessionState", this.State.ToString()); throw new InvalidOperationException("The session is not available"); } } clientMessages = this.GetClientMessages(); } return(clientMessages); } else { throw new ArgumentNullException("command"); } }
public static void InvokeCommand(this PowerShell pwsh, PSCommand psCommand, PSInvocationSettings invocationSettings = null) { pwsh.Commands = psCommand; pwsh.InvokeAndClear(invocationSettings); }
public static async Task <PSDataCollection <T2> > InvokeAsync <T1, T2>(this System.Management.Automation.PowerShell shell, PSDataCollection <T1> input = null, PSInvocationSettings invocationSettings = null) { var output = new PSDataCollection <T2>(); object state = "none"; await Task.Factory.FromAsync( (t1, t2, callback, obj) => shell.BeginInvoke(t1, t2, invocationSettings ?? new PSInvocationSettings(), callback, obj), (Action <IAsyncResult>)((a) => shell.EndInvoke(a)), input, output, state); return(output); }