internal static IEnumerable <PSObject> InvokePowerShell( PowerShell powerShell, CancellationToken cancellationToken, PSCmdlet cmdlet, string errorMessageTemplate) { CopyParameterFromCmdletToPowerShell(cmdlet, powerShell, "ErrorAction"); CopyParameterFromCmdletToPowerShell(cmdlet, powerShell, "WarningAction"); CopyParameterFromCmdletToPowerShell(cmdlet, powerShell, "InformationAction"); CopyParameterFromCmdletToPowerShell(cmdlet, powerShell, "Verbose"); CopyParameterFromCmdletToPowerShell(cmdlet, powerShell, "Debug"); var invocationSettings = new PSInvocationSettings { Host = cmdlet.Host }; // TODO/FIXME: ETW events for the output stream IEnumerable <PSObject> outputStream = powerShell.IsNested ? InvokeNestedPowerShell(powerShell, cancellationToken, cmdlet, invocationSettings, errorMessageTemplate) : InvokeTopLevelPowerShell(powerShell, cancellationToken, cmdlet, invocationSettings, errorMessageTemplate); return(EnumerateWithCatch( outputStream, delegate(Exception exception) { ErrorRecord errorRecord = GetErrorRecordForRemotePipelineInvocation(exception, errorMessageTemplate); HandleErrorFromPipeline(cmdlet, errorRecord, powerShell); })); }
private IAsyncResult Start(bool startMainPowerShell) { using (ServerPowerShellDriver.tracer.TraceMethod()) { if (startMainPowerShell) { this.dsHandler.Prepare(); } PSInvocationSettings settings = new PSInvocationSettings(); settings.ApartmentState = this.apartmentState; settings.Host = (PSHost)this.remoteHost; switch (WindowsIdentity.GetCurrent().ImpersonationLevel) { case TokenImpersonationLevel.Impersonation: case TokenImpersonationLevel.Delegation: settings.FlowImpersonationPolicy = true; break; default: settings.FlowImpersonationPolicy = false; break; } settings.AddToHistory = this.addToHistory; return(startMainPowerShell ? this.localPowerShell.BeginInvoke <object, PSObject>(this.input, this.localPowerShellOutput, settings, (AsyncCallback)null, (object)null) : this.extraPowerShell.BeginInvoke <object, PSObject>(this.input, this.localPowerShellOutput, settings, (AsyncCallback)null, (object)null)); } }
private static IEnumerable <PSObject> InvokeNestedPowerShell( PowerShell powerShell, CancellationToken cancellationToken, PSCmdlet cmdlet, PSInvocationSettings invocationSettings, string errorMessageTemplate) { EventHandler <DataAddedEventArgs> errorHandler = GetStreamForwarder <ErrorRecord>( delegate(ErrorRecord errorRecord) { errorRecord = GetErrorRecordForRemotePipelineInvocation(errorRecord, errorMessageTemplate); HandleErrorFromPipeline(cmdlet, errorRecord, powerShell); }); powerShell.Streams.Error.DataAdded += errorHandler; try { using (cancellationToken.Register(powerShell.Stop)) { // TODO/FIXME: ETW event for PowerShell invocation foreach (PSObject outputObject in powerShell.Invoke <PSObject>(null, invocationSettings)) { yield return(outputObject); } } } finally { powerShell.Streams.Error.DataAdded -= errorHandler; } }
/// <summary> /// Initializes the underlying PowerShell object after verifying that it is /// in a state where it can connect to the remote command. /// </summary> /// <param name="syncCall"></param> private void InitPowerShellForConnect(bool syncCall) { if (_pipelineStateInfo.State != PipelineState.Disconnected) { throw new InvalidPipelineStateException(StringUtil.Format(PipelineStrings.PipelineNotDisconnected), _pipelineStateInfo.State, PipelineState.Disconnected); } // The connect may be from the same Pipeline that disconnected and in this case // the Pipeline state already exists. Or this could be a new Pipeline object // (connect reconstruction case) and new state is created. // Check to see if this pipeline already exists in the runspace. RemotePipeline currentPipeline = (RemotePipeline)((RemoteRunspace)_runspace).GetCurrentlyRunningPipeline(); if (currentPipeline == null || currentPipeline != null && !ReferenceEquals(currentPipeline, this)) { ((RemoteRunspace)_runspace).DoConcurrentCheckAndAddToRunningPipelines(this, syncCall); } // Initialize the PowerShell object if it hasn't been initialized before. if ((_powershell.RemotePowerShell) == null || !_powershell.RemotePowerShell.Initialized) { PSInvocationSettings settings = new PSInvocationSettings(); settings.AddToHistory = _addToHistory; _powershell.InitForRemotePipelineConnect(_inputStream, _outputStream, _errorStream, settings, RedirectShellErrorOutputPipe); _powershell.RemotePowerShell.HostCallReceived += new EventHandler <RemoteDataEventArgs <RemoteHostCall> >(HandleHostCallReceived); } }
/// <summary> /// Invokes the Main PowerShell object synchronously. /// </summary> internal void InvokeMain() { PSInvocationSettings settings = PrepInvoke(true); Exception ex = null; try { LocalPowerShell.InvokeWithDebugger(InputCollection, _localPowerShellOutput, settings, true); } catch (Exception e) { ex = e; } if (ex != null) { // Since this is being invoked asynchronously on a single pipeline thread // any invoke failures (such as possible debugger failures) need to be // passed back to client or the original client invoke request will not respond. string failedCommand = LocalPowerShell.Commands.Commands[0].CommandText; LocalPowerShell.Commands.Clear(); string msg = StringUtil.Format( RemotingErrorIdStrings.ServerSideNestedCommandInvokeFailed, failedCommand ?? string.Empty, ex.Message ?? string.Empty); LocalPowerShell.AddCommand("Write-Error").AddArgument(msg); LocalPowerShell.Invoke(); } }
private IAsyncResult Start(bool startMainPowerShell) { if (startMainPowerShell) { this.dsHandler.Prepare(); } PSInvocationSettings settings = new PSInvocationSettings { ApartmentState = this.apartmentState, Host = this.remoteHost }; TokenImpersonationLevel impersonation = OSHelper.IsUnix ? TokenImpersonationLevel.Identification : WindowsIdentity.GetCurrent().ImpersonationLevel; switch (impersonation) { case TokenImpersonationLevel.Impersonation: case TokenImpersonationLevel.Delegation: settings.FlowImpersonationPolicy = true; break; default: settings.FlowImpersonationPolicy = false; break; } settings.AddToHistory = this.addToHistory; if (startMainPowerShell) { return(this.localPowerShell.BeginInvoke <object, PSObject>(this.input, this.localPowerShellOutput, settings, null, null)); } return(this.extraPowerShell.BeginInvoke <object, PSObject>(this.input, this.localPowerShellOutput, settings, null, null)); }
/// <summary> /// Initializes the underlying PowerShell object after verifying /// if the pipeline is in a state where it can be invoked. /// If invokeAndDisconnect is true then the remote PowerShell /// command will be immediately disconnected after it begins /// running. /// </summary> /// <param name="syncCall">true if called from a sync call</param> /// <param name="invokeAndDisconnect">Invoke and Disconnect</param> private void InitPowerShell(bool syncCall, bool invokeAndDisconnect = false) { if (_commands == null || _commands.Count == 0) { throw PSTraceSource.NewInvalidOperationException( RunspaceStrings.NoCommandInPipeline); } if (_pipelineStateInfo.State != PipelineState.NotStarted) { InvalidPipelineStateException e = new InvalidPipelineStateException ( StringUtil.Format(RunspaceStrings.PipelineReInvokeNotAllowed), _pipelineStateInfo.State, PipelineState.NotStarted ); throw e; } ((RemoteRunspace)_runspace).DoConcurrentCheckAndAddToRunningPipelines(this, syncCall); PSInvocationSettings settings = new PSInvocationSettings(); settings.AddToHistory = _addToHistory; settings.InvokeAndDisconnect = invokeAndDisconnect; _powershell.InitForRemotePipeline(_commands, _inputStream, _outputStream, _errorStream, settings, RedirectShellErrorOutputPipe); _powershell.RemotePowerShell.HostCallReceived += new EventHandler <RemoteDataEventArgs <RemoteHostCall> >(HandleHostCallReceived); }
private IAsyncResult Start(bool startMainPowerShell) { PSInvocationSettings settings = PrepInvoke(startMainPowerShell); if (startMainPowerShell) { return(LocalPowerShell.BeginInvoke <object, PSObject>(InputCollection, _localPowerShellOutput, settings, null, null)); } else { return(_extraPowerShell.BeginInvoke <object, PSObject>(InputCollection, _localPowerShellOutput, settings, null, null)); } }
private void InitPowerShell(bool syncCall, bool invokeAndDisconnect = false) { if ((this._commands == null) || (this._commands.Count == 0)) { throw PSTraceSource.NewInvalidOperationException("RunspaceStrings", "NoCommandInPipeline", new object[0]); } if (this._pipelineStateInfo.State != PipelineState.NotStarted) { InvalidPipelineStateException exception = new InvalidPipelineStateException(StringUtil.Format(RunspaceStrings.PipelineReInvokeNotAllowed, new object[0]), this._pipelineStateInfo.State, PipelineState.NotStarted); throw exception; } ((RemoteRunspace)this._runspace).DoConcurrentCheckAndAddToRunningPipelines(this, syncCall); PSInvocationSettings settings = new PSInvocationSettings { AddToHistory = this._addToHistory, InvokeAndDisconnect = invokeAndDisconnect }; this._powershell.InitForRemotePipeline(this._commands, this._inputStream, this._outputStream, this._errorStream, settings, base.RedirectShellErrorOutputPipe); this._powershell.RemotePowerShell.HostCallReceived += new EventHandler <RemoteDataEventArgs <RemoteHostCall> >(this.HandleHostCallReceived); }
internal static RemoteDataObject GenerateCreatePowerShell(ClientRemotePowerShell shell) { HostInfo info; PowerShell powerShell = shell.PowerShell; PSInvocationSettings settings = shell.Settings; PSObject data = CreateEmptyPSObject(); Guid empty = Guid.Empty; ApartmentState unknown = ApartmentState.Unknown; RunspacePool runspaceConnection = powerShell.GetRunspaceConnection() as RunspacePool; empty = runspaceConnection.InstanceId; unknown = runspaceConnection.ApartmentState; data.Properties.Add(new PSNoteProperty("PowerShell", powerShell.ToPSObjectForRemoting())); data.Properties.Add(new PSNoteProperty("NoInput", shell.NoInput)); if (settings == null) { info = new HostInfo(null) { UseRunspaceHost = true }; data.Properties.Add(new PSNoteProperty("ApartmentState", unknown)); data.Properties.Add(new PSNoteProperty("RemoteStreamOptions", RemoteStreamOptions.AddInvocationInfo)); data.Properties.Add(new PSNoteProperty("AddToHistory", false)); } else { info = new HostInfo(settings.Host); if (settings.Host == null) { info.UseRunspaceHost = true; } data.Properties.Add(new PSNoteProperty("ApartmentState", settings.ApartmentState)); data.Properties.Add(new PSNoteProperty("RemoteStreamOptions", settings.RemoteStreamOptions)); data.Properties.Add(new PSNoteProperty("AddToHistory", settings.AddToHistory)); } PSNoteProperty member = CreateHostInfoProperty(info); data.Properties.Add(member); data.Properties.Add(new PSNoteProperty("IsNested", shell.PowerShell.IsNested)); return(RemoteDataObject.CreateFrom(RemotingDestination.InvalidDestination | RemotingDestination.Server, RemotingDataType.CreatePowerShell, empty, shell.InstanceId, data)); }
private PSInvocationSettings PrepInvoke(bool startMainPowerShell) { if (startMainPowerShell) { // prepare transport manager for sending and receiving data. DataStructureHandler.Prepare(); } PSInvocationSettings settings = new PSInvocationSettings(); #if !CORECLR // No ApartmentState In CoreCLR settings.ApartmentState = apartmentState; #endif settings.Host = _remoteHost; // Flow the impersonation policy to pipeline execution thread // only if the current thread is impersonated (Delegation is // also a kind of impersonation). if (Platform.IsWindows) { WindowsIdentity currentThreadIdentity = WindowsIdentity.GetCurrent(); switch (currentThreadIdentity.ImpersonationLevel) { case TokenImpersonationLevel.Impersonation: case TokenImpersonationLevel.Delegation: settings.FlowImpersonationPolicy = true; break; default: settings.FlowImpersonationPolicy = false; break; } } else { settings.FlowImpersonationPolicy = false; } settings.AddToHistory = _addToHistory; return(settings); }
private void InitPowerShellForConnect(bool syncCall) { if (this._pipelineStateInfo.State != PipelineState.Disconnected) { throw new InvalidPipelineStateException(StringUtil.Format(PipelineStrings.PipelineNotDisconnected, new object[0]), this._pipelineStateInfo.State, PipelineState.Disconnected); } RemotePipeline currentlyRunningPipeline = (RemotePipeline)((RemoteRunspace)this._runspace).GetCurrentlyRunningPipeline(); if ((currentlyRunningPipeline == null) || ((currentlyRunningPipeline != null) && !object.ReferenceEquals(currentlyRunningPipeline, this))) { ((RemoteRunspace)this._runspace).DoConcurrentCheckAndAddToRunningPipelines(this, syncCall); } if ((this._powershell.RemotePowerShell == null) || !this._powershell.RemotePowerShell.Initialized) { PSInvocationSettings settings = new PSInvocationSettings { AddToHistory = this._addToHistory }; this._powershell.InitForRemotePipelineConnect(this._inputStream, this._outputStream, this._errorStream, settings, base.RedirectShellErrorOutputPipe); this._powershell.RemotePowerShell.HostCallReceived += new EventHandler <RemoteDataEventArgs <RemoteHostCall> >(this.HandleHostCallReceived); } }
internal static RemoteDataObject GenerateCreatePowerShell( ClientRemotePowerShell shell) { PowerShell powerShell = shell.PowerShell; PSInvocationSettings settings = shell.Settings; PSObject emptyPsObject = RemotingEncoder.CreateEmptyPSObject(); Guid empty = Guid.Empty; RunspacePool runspaceConnection = powerShell.GetRunspaceConnection() as RunspacePool; Guid instanceId = runspaceConnection.InstanceId; ApartmentState apartmentState = runspaceConnection.ApartmentState; emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("PowerShell", (object)powerShell.ToPSObjectForRemoting())); emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("NoInput", (object)shell.NoInput)); HostInfo hostInfo; if (settings == null) { hostInfo = new HostInfo((PSHost)null); hostInfo.UseRunspaceHost = true; emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("ApartmentState", (object)apartmentState)); emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("RemoteStreamOptions", (object)RemoteStreamOptions.AddInvocationInfo)); emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("AddToHistory", (object)false)); } else { hostInfo = new HostInfo(settings.Host); if (settings.Host == null) { hostInfo.UseRunspaceHost = true; } emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("ApartmentState", (object)settings.ApartmentState)); emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("RemoteStreamOptions", (object)settings.RemoteStreamOptions)); emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("AddToHistory", (object)settings.AddToHistory)); } PSNoteProperty hostInfoProperty = RemotingEncoder.CreateHostInfoProperty(hostInfo); emptyPsObject.Properties.Add((PSPropertyInfo)hostInfoProperty); return(RemoteDataObject.CreateFrom(RemotingDestination.Server, RemotingDataType.CreatePowerShell, instanceId, shell.InstanceId, (object)emptyPsObject)); }
private static void BeginInvokeOnPowershellCommand(System.Management.Automation.PowerShell ps, PSDataCollection<object> varsInput, PSInvocationSettings settings, AsyncCallback callback, RunCommandsArguments args) { PowerShellTraceSource traceSource = PowerShellTraceSourceFactory.GetTraceSource(); using (traceSource) { try { ps.BeginInvoke<object>(varsInput, settings, callback, args); } catch (Exception exception1) { Exception exception = exception1; bool flag = PSActivity.ProcessException(args, exception); if (!flag) { PSActivity.ReleaseResourcesAndCheckForEnd(ps, args, false, false); } else { PSActivity.BeginActionRetry(args); } traceSource.TraceException(exception); } } }
private static IEnumerable <PSObject> InvokeTopLevelPowerShell(PowerShell powerShell, CancellationToken cancellationToken, PSCmdlet cmdlet, PSInvocationSettings invocationSettings, string errorMessageTemplate) { Action <PSObject> action = null; Action <ErrorRecord> action1 = null; Action <WarningRecord> action2 = null; Action <VerboseRecord> action3 = null; Action <DebugRecord> action4 = null; AsyncCallback asyncCallback = null; using (BlockingCollection <Func <PSCmdlet, IEnumerable <PSObject> > > funcs = new BlockingCollection <Func <PSCmdlet, IEnumerable <PSObject> > >(RemoteDiscoveryHelper.BlockingCollectionCapacity)) { PSDataCollection <PSObject> pSObjects = new PSDataCollection <PSObject>(); if (action == null) { action = (PSObject output) => funcs.Add((PSCmdlet argument0) => { PSObject[] pSObjectArray = new PSObject[1]; pSObjectArray[0] = output; return(pSObjectArray); } ); } EventHandler <DataAddedEventArgs> streamForwarder = RemoteDiscoveryHelper.GetStreamForwarder <PSObject>(action, true); if (action1 == null) { action1 = (ErrorRecord errorRecord) => funcs.Add((PSCmdlet c) => { errorRecord = RemoteDiscoveryHelper.GetErrorRecordForRemotePipelineInvocation(errorRecord, errorMessageTemplate); RemoteDiscoveryHelper.HandleErrorFromPipeline(c, errorRecord, powerShell); return(Enumerable.Empty <PSObject>()); } ); } EventHandler <DataAddedEventArgs> eventHandler = RemoteDiscoveryHelper.GetStreamForwarder <ErrorRecord>(action1, true); if (action2 == null) { action2 = (WarningRecord warningRecord) => funcs.Add((PSCmdlet c) => { c.WriteWarning(warningRecord.Message); return(Enumerable.Empty <PSObject>()); } ); } EventHandler <DataAddedEventArgs> streamForwarder1 = RemoteDiscoveryHelper.GetStreamForwarder <WarningRecord>(action2, true); if (action3 == null) { action3 = (VerboseRecord verboseRecord) => funcs.Add((PSCmdlet c) => { c.WriteVerbose(verboseRecord.Message); return(Enumerable.Empty <PSObject>()); } ); } EventHandler <DataAddedEventArgs> eventHandler1 = RemoteDiscoveryHelper.GetStreamForwarder <VerboseRecord>(action3, true); if (action4 == null) { action4 = (DebugRecord debugRecord) => funcs.Add((PSCmdlet c) => { c.WriteDebug(debugRecord.Message); return(Enumerable.Empty <PSObject>()); } ); } EventHandler <DataAddedEventArgs> streamForwarder2 = RemoteDiscoveryHelper.GetStreamForwarder <DebugRecord>(action4, true); pSObjects.DataAdded += streamForwarder; powerShell.Streams.Error.DataAdded += eventHandler; powerShell.Streams.Warning.DataAdded += streamForwarder1; powerShell.Streams.Verbose.DataAdded += eventHandler1; powerShell.Streams.Debug.DataAdded += streamForwarder2; try { PowerShell powerShell1 = powerShell; object obj = null; PSDataCollection <PSObject> pSObjects1 = pSObjects; PSInvocationSettings pSInvocationSetting = invocationSettings; if (asyncCallback == null) { asyncCallback = (IAsyncResult param0) => { try { funcs.CompleteAdding(); } catch (InvalidOperationException invalidOperationException) { } } ; } IAsyncResult asyncResult = powerShell1.BeginInvoke <PSObject, PSObject>((PSDataCollection <PSObject>)obj, pSObjects1, pSInvocationSetting, asyncCallback, null); CancellationTokenRegistration cancellationTokenRegistration = cancellationToken.Register(new Action(powerShell.Stop)); try { try { foreach (Func <PSCmdlet, IEnumerable <PSObject> > func in funcs) { IEnumerator <PSObject> enumerator = func(cmdlet).GetEnumerator(); using (enumerator) { while (enumerator.MoveNext()) { yield return(enumerator.Current); } } } } finally { funcs.CompleteAdding(); powerShell.EndInvoke(asyncResult); } } finally { cancellationTokenRegistration.Dispose(); } } finally { pSObjects.DataAdded -= streamForwarder; powerShell.Streams.Error.DataAdded -= eventHandler; powerShell.Streams.Warning.DataAdded -= streamForwarder1; powerShell.Streams.Verbose.DataAdded -= eventHandler1; powerShell.Streams.Debug.DataAdded -= streamForwarder2; } } }
private static IEnumerable <PSObject> InvokeNestedPowerShell(PowerShell powerShell, CancellationToken cancellationToken, PSCmdlet cmdlet, PSInvocationSettings invocationSettings, string errorMessageTemplate) { EventHandler <DataAddedEventArgs> streamForwarder = GetStreamForwarder <ErrorRecord>(delegate(ErrorRecord errorRecord) { errorRecord = GetErrorRecordForRemotePipelineInvocation(errorRecord, errorMessageTemplate); HandleErrorFromPipeline(cmdlet, errorRecord, powerShell); }, false); powerShell.Streams.Error.DataAdded += streamForwarder; using (cancellationToken.Register(new Action(powerShell.Stop))) { foreach (PSObject iteratorVariable1 in powerShell.Invoke <PSObject>(null, invocationSettings)) { yield return(iteratorVariable1); } } }
private DebuggerCommandResults ProcessDebugCommand(string cmd, out Exception e) { DebuggerCommandResults results = null; try { _parent.DebuggerCanStopCommand = true; // Use PowerShell object to write streaming data to host. using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create()) { PSInvocationSettings settings = new PSInvocationSettings() { Host = _parent }; PSDataCollection<PSObject> output = new PSDataCollection<PSObject>(); ps.AddCommand("Out-Default"); IAsyncResult async = ps.BeginInvoke<PSObject>(output, settings, null, null); // Let debugger evaluate command and stream output data. results = _parent.Runspace.Debugger.ProcessCommand( new PSCommand( new Command(cmd, true)), output); output.Complete(); ps.EndInvoke(async); } e = null; } catch (Exception ex) { ConsoleHost.CheckForSevereException(ex); e = ex; results = new DebuggerCommandResults(null, false); } finally { _parent.DebuggerCanStopCommand = false; } // Exit debugger if command fails to evaluate. return results ?? new DebuggerCommandResults(DebuggerResumeAction.Continue, false); }
public void Invoke<T>(IEnumerable input, IList<T> output, PSInvocationSettings settings) { throw new NotImplementedException(); }
private void WorkerMain(int id) { var host = new WorkerHost(_host, id); try { host.UI.WriteLine("Starting"); var shell = PowerShell.Create(); var state = shell.Runspace.SessionStateProxy; foreach (DictionaryEntry entry in _parameters) state.SetVariable(entry.Key.ToString(), entry.Value); state.SetVariable("RunId", _runId); state.SetVariable("Modules", new ModuleDispenser(id, this)); var settings = new PSInvocationSettings { Host = host, ErrorActionPreference = ActionPreference.Stop }; shell.AddScript(_script).Invoke(null, settings); } catch (Exception e) { host.UI.WriteErrorLine(e.Message); throw; } finally { host.UI.WriteLine("Ended"); SetEnding(); } }
private void InitPowerShell(bool syncCall, bool invokeAndDisconnect = false) { if ((this._commands == null) || (this._commands.Count == 0)) { throw PSTraceSource.NewInvalidOperationException("RunspaceStrings", "NoCommandInPipeline", new object[0]); } if (this._pipelineStateInfo.State != PipelineState.NotStarted) { InvalidPipelineStateException exception = new InvalidPipelineStateException(StringUtil.Format(RunspaceStrings.PipelineReInvokeNotAllowed, new object[0]), this._pipelineStateInfo.State, PipelineState.NotStarted); throw exception; } ((RemoteRunspace) this._runspace).DoConcurrentCheckAndAddToRunningPipelines(this, syncCall); PSInvocationSettings settings = new PSInvocationSettings { AddToHistory = this._addToHistory, InvokeAndDisconnect = invokeAndDisconnect }; this._powershell.InitForRemotePipeline(this._commands, this._inputStream, this._outputStream, this._errorStream, settings, base.RedirectShellErrorOutputPipe); this._powershell.RemotePowerShell.HostCallReceived += new EventHandler<RemoteDataEventArgs<RemoteHostCall>>(this.HandleHostCallReceived); }
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); }
private PSInvocationSettings PrepInvoke(bool startMainPowerShell) { if (startMainPowerShell) { // prepare transport manager for sending and receiving data. DataStructureHandler.Prepare(); } PSInvocationSettings settings = new PSInvocationSettings(); #if !CORECLR // No ApartmentState In CoreCLR settings.ApartmentState = apartmentState; #endif settings.Host = _remoteHost; // Flow the impersonation policy to pipeline execution thread // only if the current thread is impersonated (Delegation is // also a kind of impersonation). if (Platform.IsWindows) { WindowsIdentity currentThreadIdentity = WindowsIdentity.GetCurrent(); switch (currentThreadIdentity.ImpersonationLevel) { case TokenImpersonationLevel.Impersonation: case TokenImpersonationLevel.Delegation: settings.FlowImpersonationPolicy = true; break; default: settings.FlowImpersonationPolicy = false; break; } } else { settings.FlowImpersonationPolicy = false; } settings.AddToHistory = _addToHistory; return settings; }
public IAsyncResult BeginInvoke<TInput, TOutput>(PSDataCollection<TInput> input, PSDataCollection<TOutput> output, PSInvocationSettings settings, AsyncCallback callback, object state) { throw new NotImplementedException(); }
private void InitPowerShellForConnect(bool syncCall) { if (this._pipelineStateInfo.State != PipelineState.Disconnected) { throw new InvalidPipelineStateException(StringUtil.Format(PipelineStrings.PipelineNotDisconnected, new object[0]), this._pipelineStateInfo.State, PipelineState.Disconnected); } RemotePipeline currentlyRunningPipeline = (RemotePipeline) ((RemoteRunspace) this._runspace).GetCurrentlyRunningPipeline(); if ((currentlyRunningPipeline == null) || ((currentlyRunningPipeline != null) && !object.ReferenceEquals(currentlyRunningPipeline, this))) { ((RemoteRunspace) this._runspace).DoConcurrentCheckAndAddToRunningPipelines(this, syncCall); } if ((this._powershell.RemotePowerShell == null) || !this._powershell.RemotePowerShell.Initialized) { PSInvocationSettings settings = new PSInvocationSettings { AddToHistory = this._addToHistory }; this._powershell.InitForRemotePipelineConnect(this._inputStream, this._outputStream, this._errorStream, settings, base.RedirectShellErrorOutputPipe); this._powershell.RemotePowerShell.HostCallReceived += new EventHandler<RemoteDataEventArgs<RemoteHostCall>>(this.HandleHostCallReceived); } }
internal static void ContinueCommand(RemoteRunspace remoteRunspace, Pipeline cmd, PSHost host, bool inDebugMode, System.Management.Automation.ExecutionContext context) { RemotePipeline remotePipeline = cmd as RemotePipeline; if (remotePipeline != null) { using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create()) { PSInvocationSettings settings = new PSInvocationSettings() { Host = host }; PSDataCollection<PSObject> input = new PSDataCollection<PSObject>(); CommandInfo commandInfo = new CmdletInfo("Out-Default", typeof(OutDefaultCommand), null, null, context); Command outDefaultCommand = new Command(commandInfo); ps.AddCommand(outDefaultCommand); IAsyncResult async = ps.BeginInvoke<PSObject>(input, settings, null, null); RemoteDebugger remoteDebugger = remoteRunspace.Debugger as RemoteDebugger; if (remoteDebugger != null) { // Update client with breakpoint information from pushed runspace. // Information will be passed to the client via the Debugger.BreakpointUpdated event. remoteDebugger.SendBreakpointUpdatedEvents(); if (!inDebugMode) { // Enter debug mode if remote runspace is in debug stop mode. remoteDebugger.CheckStateAndRaiseStopEvent(); } } // Wait for debugged cmd to complete. while (!remotePipeline.Output.EndOfPipeline) { remotePipeline.Output.WaitHandle.WaitOne(); while (remotePipeline.Output.Count > 0) { input.Add(remotePipeline.Output.Read()); } } input.Complete(); ps.EndInvoke(async); } } }
/// <summary> /// Initializes the underlying PowerShell object after verifying /// if the pipeline is in a state where it can be invoked. /// If invokeAndDisconnect is true then the remote PowerShell /// command will be immediately disconnected after it begins /// running. /// </summary> /// <param name="syncCall">true if called from a sync call</param> /// <param name="invokeAndDisconnect">Invoke and Disconnect</param> private void InitPowerShell(bool syncCall, bool invokeAndDisconnect = false) { if (_commands == null || _commands.Count == 0) { throw PSTraceSource.NewInvalidOperationException( RunspaceStrings.NoCommandInPipeline); } if (_pipelineStateInfo.State != PipelineState.NotStarted) { InvalidPipelineStateException e = new InvalidPipelineStateException ( StringUtil.Format(RunspaceStrings.PipelineReInvokeNotAllowed), _pipelineStateInfo.State, PipelineState.NotStarted ); throw e; } ((RemoteRunspace)_runspace).DoConcurrentCheckAndAddToRunningPipelines(this, syncCall); PSInvocationSettings settings = new PSInvocationSettings(); settings.AddToHistory = _addToHistory; settings.InvokeAndDisconnect = invokeAndDisconnect; _powershell.InitForRemotePipeline(_commands, _inputStream, _outputStream, _errorStream, settings, RedirectShellErrorOutputPipe); _powershell.RemotePowerShell.HostCallReceived += new EventHandler<RemoteDataEventArgs<RemoteHostCall>>(HandleHostCallReceived); }
public Collection<T> Invoke<T>(IEnumerable input, PSInvocationSettings settings) { throw new NotImplementedException(); }
private static IEnumerable <PSObject> InvokeTopLevelPowerShell( PowerShell powerShell, CancellationToken cancellationToken, PSCmdlet cmdlet, PSInvocationSettings invocationSettings, string errorMessageTemplate) { using (var mergedOutput = new BlockingCollection <Func <PSCmdlet, IEnumerable <PSObject> > >(s_blockingCollectionCapacity)) { var asyncOutput = new PSDataCollection <PSObject>(); EventHandler <DataAddedEventArgs> outputHandler = GetStreamForwarder <PSObject>( output => mergedOutput.Add(_ => new[] { output }), swallowInvalidOperationExceptions: true); EventHandler <DataAddedEventArgs> errorHandler = GetStreamForwarder <ErrorRecord>( errorRecord => mergedOutput.Add( delegate(PSCmdlet c) { errorRecord = GetErrorRecordForRemotePipelineInvocation(errorRecord, errorMessageTemplate); HandleErrorFromPipeline(c, errorRecord, powerShell); return(Enumerable.Empty <PSObject>()); }), swallowInvalidOperationExceptions: true); EventHandler <DataAddedEventArgs> warningHandler = GetStreamForwarder <WarningRecord>( warningRecord => mergedOutput.Add( delegate(PSCmdlet c) { c.WriteWarning(warningRecord.Message); return(Enumerable.Empty <PSObject>()); }), swallowInvalidOperationExceptions: true); EventHandler <DataAddedEventArgs> verboseHandler = GetStreamForwarder <VerboseRecord>( verboseRecord => mergedOutput.Add( delegate(PSCmdlet c) { c.WriteVerbose(verboseRecord.Message); return(Enumerable.Empty <PSObject>()); }), swallowInvalidOperationExceptions: true); EventHandler <DataAddedEventArgs> debugHandler = GetStreamForwarder <DebugRecord>( debugRecord => mergedOutput.Add( delegate(PSCmdlet c) { c.WriteDebug(debugRecord.Message); return(Enumerable.Empty <PSObject>()); }), swallowInvalidOperationExceptions: true); EventHandler <DataAddedEventArgs> informationHandler = GetStreamForwarder <InformationRecord>( informationRecord => mergedOutput.Add( delegate(PSCmdlet c) { c.WriteInformation(informationRecord); return(Enumerable.Empty <PSObject>()); }), swallowInvalidOperationExceptions: true); asyncOutput.DataAdded += outputHandler; powerShell.Streams.Error.DataAdded += errorHandler; powerShell.Streams.Warning.DataAdded += warningHandler; powerShell.Streams.Verbose.DataAdded += verboseHandler; powerShell.Streams.Debug.DataAdded += debugHandler; powerShell.Streams.Information.DataAdded += informationHandler; try { // TODO/FIXME: ETW event for PowerShell invocation var asyncResult = powerShell.BeginInvoke <PSObject, PSObject>( input: null, output: asyncOutput, settings: invocationSettings, callback: delegate { try { mergedOutput.CompleteAdding(); } catch (InvalidOperationException) // ignore exceptions thrown because mergedOutput.CompleteAdding was called { } }, state: null); using (cancellationToken.Register(powerShell.Stop)) { try { foreach (Func <PSCmdlet, IEnumerable <PSObject> > mergedOutputItem in mergedOutput.GetConsumingEnumerable()) { foreach (PSObject outputObject in mergedOutputItem(cmdlet)) { yield return(outputObject); } } } finally { mergedOutput.CompleteAdding(); powerShell.EndInvoke(asyncResult); } } } finally { asyncOutput.DataAdded -= outputHandler; powerShell.Streams.Error.DataAdded -= errorHandler; powerShell.Streams.Warning.DataAdded -= warningHandler; powerShell.Streams.Verbose.DataAdded -= verboseHandler; powerShell.Streams.Debug.DataAdded -= debugHandler; powerShell.Streams.Information.DataAdded -= informationHandler; } } }
private IAsyncResult Start(bool startMainPowerShell) { if (startMainPowerShell) { this.dsHandler.Prepare(); } PSInvocationSettings settings = new PSInvocationSettings { ApartmentState = this.apartmentState, Host = this.remoteHost }; TokenImpersonationLevel impersonation = OSHelper.IsUnix ? TokenImpersonationLevel.Identification : WindowsIdentity.GetCurrent().ImpersonationLevel; switch (impersonation) { case TokenImpersonationLevel.Impersonation: case TokenImpersonationLevel.Delegation: settings.FlowImpersonationPolicy = true; break; default: settings.FlowImpersonationPolicy = false; break; } settings.AddToHistory = this.addToHistory; if (startMainPowerShell) { return this.localPowerShell.BeginInvoke<object, PSObject>(this.input, this.localPowerShellOutput, settings, null, null); } return this.extraPowerShell.BeginInvoke<object, PSObject>(this.input, this.localPowerShellOutput, settings, null, null); }
/// <summary> /// Initializes the underlying PowerShell object after verifying that it is /// in a state where it can connect to the remote command. /// </summary> /// <param name="syncCall"></param> private void InitPowerShellForConnect(bool syncCall) { if (_pipelineStateInfo.State != PipelineState.Disconnected) { throw new InvalidPipelineStateException(StringUtil.Format(PipelineStrings.PipelineNotDisconnected), _pipelineStateInfo.State, PipelineState.Disconnected); } // The connect may be from the same Pipeline that disconnected and in this case // the Pipeline state already exists. Or this could be a new Pipeline object // (connect reconstruction case) and new state is created. // Check to see if this pipeline already exists in the runspace. RemotePipeline currentPipeline = (RemotePipeline)((RemoteRunspace)_runspace).GetCurrentlyRunningPipeline(); if (currentPipeline == null || currentPipeline != null && !ReferenceEquals(currentPipeline, this)) { ((RemoteRunspace)_runspace).DoConcurrentCheckAndAddToRunningPipelines(this, syncCall); } // Initialize the PowerShell object if it hasn't been initialized before. if ((_powershell.RemotePowerShell) == null || !_powershell.RemotePowerShell.Initialized) { PSInvocationSettings settings = new PSInvocationSettings(); settings.AddToHistory = _addToHistory; _powershell.InitForRemotePipelineConnect(_inputStream, _outputStream, _errorStream, settings, RedirectShellErrorOutputPipe); _powershell.RemotePowerShell.HostCallReceived += new EventHandler<RemoteDataEventArgs<RemoteHostCall>>(HandleHostCallReceived); } }
public static PSInvocationSettings GetPSInvocationSettings() { PSInvocationSettings pSInvocationSetting = new PSInvocationSettings(); pSInvocationSetting.FlowImpersonationPolicy = true; return pSInvocationSetting; }