public PSTestScope(bool connect = true)
        {
            SiteUrl = ConfigurationManager.AppSettings["SPODevSiteUrl"];
            CredentialManagerEntry = ConfigurationManager.AppSettings["SPOCredentialManagerLabel"];

            var iss = InitialSessionState.CreateDefault();
            if (connect)
            {
                SessionStateCmdletEntry ssce = new SessionStateCmdletEntry("Connect-SPOnline", typeof(ConnectSPOnline), null);

                iss.Commands.Add(ssce);
            }
            _runSpace = RunspaceFactory.CreateRunspace(iss);

            _runSpace.Open();

            if (connect)
            {
                var pipeLine = _runSpace.CreatePipeline();
                Command cmd = new Command("connect-sponline");
                cmd.Parameters.Add("Url", SiteUrl);
                if (!string.IsNullOrEmpty(CredentialManagerEntry))
                {
                    cmd.Parameters.Add("Credentials", CredentialManagerEntry);
                }
                pipeLine.Commands.Add(cmd);
                pipeLine.Invoke();
            }
        }
        /// <summary>
        /// Creates a new class and stores the passed values containing connection information
        /// </summary>
        /// <param name="uri">The URI to the Exchange powershell virtual directory</param>
        /// <param name="username">DOMAIN\Username to authenticate with</param>
        /// <param name="password">Password for the domain user</param>
        /// <param name="isKerberos">True if using kerberos authentication, False if using basic authentication</param>
        /// <param name="domainController">The domain controller to communicate with</param>
        public ExchPowershell()
        {
            try
            {
                // Retrieve the settings from the database
                SchedulerRetrieve.GetSettings();

                // Set our domain controller to communicate with
                this.domainController = Config.PrimaryDC;

                // Get the type of Exchange connection
                bool isKerberos = false;
                if (Config.ExchangeConnectionType == Enumerations.ConnectionType.Kerberos)
                    isKerberos = true;

                // Create our connection
                this.wsConn = GetConnection(Config.ExchangeURI, Config.Username, Config.Password, isKerberos);

                // Create our runspace
                runspace = RunspaceFactory.CreateRunspace(wsConn);

                // Open our connection
                runspace.Open();
            }
            catch (Exception ex)
            {
                // ERROR
                logger.Fatal("Unable to establish connection to Exchange.", ex);
            }
        }
Example #3
0
        /// <summary>
        /// Create a Pipeline with an existing command string.
        /// Caller should validate all the parameters.
        /// </summary>
        /// <param name="runspace">
        /// The LocalRunspace to associate with this pipeline.
        /// </param>
        /// <param name="command">
        /// The command to invoke.
        /// </param>
        /// <param name="addToHistory"> 
        /// If true, add the command to history.
        /// </param>
        /// <param name="isNested">
        /// If true, mark this pipeline as a nested pipeline.
        /// </param>
        /// <param name="inputStream">
        /// Stream to use for reading input objects.
        /// </param>
        /// <param name="errorStream">
        /// Stream to use for writing error objects.
        /// </param>
        /// <param name="outputStream">
        /// Stream to use for writing output objects.
        /// </param>
        /// <param name="infoBuffers">
        /// Buffers used to write progress, verbose, debug, warning, information
        /// information of an invocation.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// Command is null and add to history is true
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// 1. InformationalBuffers is null
        /// </exception>
        protected PipelineBase(Runspace runspace,
            CommandCollection command,
            bool addToHistory,
            bool isNested,
            ObjectStreamBase inputStream,
            ObjectStreamBase outputStream,
            ObjectStreamBase errorStream,
            PSInformationalBuffers infoBuffers)
            : base(runspace, command)
        {
            Dbg.Assert(null != inputStream, "Caller Should validate inputstream parameter");
            Dbg.Assert(null != outputStream, "Caller Should validate outputStream parameter");
            Dbg.Assert(null != errorStream, "Caller Should validate errorStream parameter");
            Dbg.Assert(null != infoBuffers, "Caller Should validate informationalBuffers parameter");
            Dbg.Assert(null != command, "Command cannot be null");

            // Since we are constructing this pipeline using a commandcollection we dont need
            // to add cmd to CommandCollection again (Initialize does this).. because of this
            // I am handling history here..
            Initialize(runspace, null, false, isNested);
            if (true == addToHistory)
            {
                // get command text for history..
                string cmdText = command.GetCommandStringForHistory();
                HistoryString = cmdText;
                AddToHistory = addToHistory;
            }

            //Initialize streams
            InputStream = inputStream;
            OutputStream = outputStream;
            ErrorStream = errorStream;
            InformationalBuffers = infoBuffers;
        }
        /// <summary>
        /// Gets the command's "Synopsis" documentation section.
        /// </summary>
        /// <param name="commandInfo">The CommandInfo instance for the command.</param>
        /// <param name="runspace">The Runspace to use for getting command documentation.</param>
        /// <returns></returns>
        public static string GetCommandSynopsis(
            CommandInfo commandInfo, 
            Runspace runspace)
        {
            string synopsisString = string.Empty;

            PSObject helpObject = null;

            using (PowerShell powerShell = PowerShell.Create())
            {
                powerShell.Runspace = runspace;
                powerShell.AddCommand("Get-Help");
                powerShell.AddArgument(commandInfo);
                helpObject = powerShell.Invoke<PSObject>().FirstOrDefault();
            }

            if (helpObject != null)
            {
                // Extract the synopsis string from the object
                synopsisString =
                    (string)helpObject.Properties["synopsis"].Value ??
                    string.Empty;

                // Ignore the placeholder value for this field
                if (string.Equals(synopsisString, "SHORT DESCRIPTION", System.StringComparison.InvariantCultureIgnoreCase))
                {
                    synopsisString = string.Empty;
                }
            }

            return synopsisString;
        }
Example #5
0
 public static Collection<PSObject> RawExecute(string[] commands)
 {
     LastRawResults = null;
     LastUsedRunspace = InitialSessionState == null ?
         RunspaceFactory.CreateRunspace() : RunspaceFactory.CreateRunspace(InitialSessionState);
     LastUsedRunspace.Open();
     foreach (var command in commands)
     {
         using (var pipeline = LastUsedRunspace.CreatePipeline())
         {
             pipeline.Commands.AddScript(command, true);
             try
             {
                 LastRawResults = pipeline.Invoke();
             }
             catch (Exception)
             {
                 LastRawResults = pipeline.Output.ReadToEnd();
                 throw;
             }
             if (pipeline.Error.Count > 0)
             {
                 throw new MethodInvocationException(String.Join(Environment.NewLine, pipeline.Error.ReadToEnd()));
             }
         }
     }
     return LastRawResults;
 }
Example #6
0
        public ScriptDebugger(bool overrideExecutionPolicy, DTE2 dte2)
        {
            HostUi = new HostUi(this);

            InitialSessionState iss = InitialSessionState.CreateDefault();
            iss.ApartmentState = ApartmentState.STA;
            iss.ThreadOptions = PSThreadOptions.ReuseThread;


            _runspace = RunspaceFactory.CreateRunspace(this, iss);
            _runspace.Open();

            _runspaceRef = new RunspaceRef(_runspace);
            //TODO: I think this is a v4 thing. Probably need to look into it.
            //_runspaceRef.Runspace.Debugger.SetDebugMode(DebugModes.LocalScript | DebugModes.RemoteScript);
            
            //Provide access to the DTE via PowerShell. 
            //This also allows PoshTools to support StudioShell.
            _runspace.SessionStateProxy.PSVariable.Set("dte", dte2);
            ImportPoshToolsModule();
            LoadProfile();

            if (overrideExecutionPolicy)
            {
                SetupExecutionPolicy();
            }

            SetRunspace(Runspace);
        }
        public void InitializeTests()
        {

            RunspaceConfiguration config = RunspaceConfiguration.Create();
            
            PSSnapInException warning;

            config.AddPSSnapIn("ShareFile", out warning);

            runspace = RunspaceFactory.CreateRunspace(config);
            runspace.Open();

            // do login first to start tests
            using (Pipeline pipeline = runspace.CreatePipeline())
            {

                Command command = new Command("Get-SfClient");
                command.Parameters.Add(new CommandParameter("Name", Utils.LoginFilePath));

                pipeline.Commands.Add(command);

                Collection<PSObject> objs = pipeline.Invoke();
                Assert.AreEqual<int>(1, objs.Count);
                sfLogin = objs[0];
            }
        }
        internal SymbolDetails(
            SymbolReference symbolReference, 
            Runspace runspace)
        {
            this.SymbolReference = symbolReference;

            // If the symbol is a command, get its documentation
            if (symbolReference.SymbolType == SymbolType.Function)
            {
                CommandInfo commandInfo =
                    CommandHelpers.GetCommandInfo(
                        symbolReference.SymbolName,
                        runspace);

                this.Documentation =
                    CommandHelpers.GetCommandSynopsis(
                        commandInfo,
                        runspace);

                this.DisplayString = "function " + symbolReference.SymbolName;
            }
            else if (symbolReference.SymbolType == SymbolType.Parameter)
            {
                // TODO: Get parameter help
                this.DisplayString = "(parameter) " + symbolReference.SymbolName;
            }
            else if (symbolReference.SymbolType == SymbolType.Variable)
            {
                this.DisplayString = symbolReference.SymbolName;
            }
        }
Example #9
0
        public HookInjection(
            RemoteHooking.IContext InContext,
            String InChannelName,
            String entryPoint,
            String dll,
            String returnType,
            String scriptBlock,
            String modulePath,
            String additionalCode,
            bool eventLog)
        {
            Log("Opening hook interface channel...", eventLog);
            Interface = RemoteHooking.IpcConnectClient<HookInterface>(InChannelName);
            try
            {
                Runspace = RunspaceFactory.CreateRunspace();
                Runspace.Open();

                //Runspace.SessionStateProxy.SetVariable("HookInterface", Interface);
            }
            catch (Exception ex)
            {
                Log("Failed to open PowerShell runspace." + ex.Message, eventLog);
                Interface.ReportError(RemoteHooking.GetCurrentProcessId(), ex);
            }
        }
Example #10
0
 /// <summary>
 /// Constructor for RunspaceRef.
 /// </summary>
 internal RunspaceRef(Runspace runspace)
 {
     Dbg.Assert(runspace != null, "Expected runspace != null");
     _runspaceRef = new ObjectRef<Runspace>(runspace);
     _stopInvoke = false;
     _localSyncObject = new object();
 }
Example #11
0
 /// <summary>
 /// Sets the name on a runspace. This WILL FAIL for PowerShell v3!
 /// </summary>
 /// <param name="Runspace">The runspace to be named</param>
 private void SetName(System.Management.Automation.Runspaces.Runspace Runspace)
 {
     #if (NORUNSPACENAME)
     #else
     Runspace.Name = Name;
     #endif
 }
Example #12
0
 private RemotePipeline(RemoteRunspace runspace, bool addToHistory, bool isNested) : base(runspace)
 {
     this._syncRoot            = new object();
     this._pipelineStateInfo   = new System.Management.Automation.Runspaces.PipelineStateInfo(PipelineState.NotStarted);
     this._commands            = new CommandCollection();
     this._executionEventQueue = new Queue <ExecutionEventQueueItem>();
     this._performNestedCheck  = true;
     this._addToHistory        = addToHistory;
     this._isNested            = isNested;
     this._isSteppable         = false;
     this._runspace            = runspace;
     this._computerName        = ((RemoteRunspace)this._runspace).ConnectionInfo.ComputerName;
     this._runspaceId          = this._runspace.InstanceId;
     this._inputCollection     = new PSDataCollection <object>();
     this._inputCollection.ReleaseOnEnumeration = true;
     this._inputStream                   = new PSDataCollectionStream <object>(Guid.Empty, this._inputCollection);
     this._outputCollection              = new PSDataCollection <PSObject>();
     this._outputStream                  = new PSDataCollectionStream <PSObject>(Guid.Empty, this._outputCollection);
     this._errorCollection               = new PSDataCollection <ErrorRecord>();
     this._errorStream                   = new PSDataCollectionStream <ErrorRecord>(Guid.Empty, this._errorCollection);
     this._methodExecutorStream          = new ObjectStream();
     this._isMethodExecutorStreamEnabled = false;
     base.SetCommandCollection(this._commands);
     this._pipelineFinishedEvent = new ManualResetEvent(false);
 }
Example #13
0
        /// <summary>
        /// Constructor for ServerRemoteHost.
        /// </summary>
        internal ServerRemoteHost(
            Guid clientRunspacePoolId,
            Guid clientPowerShellId,
            HostInfo hostInfo,
            AbstractServerTransportManager transportManager,
            Runspace runspace,
            ServerDriverRemoteHost serverDriverRemoteHost)
        {
            _clientRunspacePoolId = clientRunspacePoolId;
            _clientPowerShellId = clientPowerShellId;
            Dbg.Assert(hostInfo != null, "Expected hostInfo != null");
            Dbg.Assert(transportManager != null, "Expected transportManager != null");

            // Set host-info and the transport-manager.
            HostInfo = hostInfo;
            _transportManager = transportManager;
            _serverDriverRemoteHost = serverDriverRemoteHost;

            // Create the executor for the host methods.
            _serverMethodExecutor = new ServerMethodExecutor(
                clientRunspacePoolId, clientPowerShellId, _transportManager);

            // Use HostInfo to create host-UI as null or non-null based on the client's host-UI.
            _remoteHostUserInterface = hostInfo.IsHostUINull ? null : new ServerRemoteHostUserInterface(this);

            Runspace = runspace;
        }
 /// <summary>
 /// Disposes the RunspaceHandle once the holder is done using it.
 /// Causes the handle to be released back to the PowerShellContext.
 /// </summary>
 public void Dispose()
 {
     // Release the handle and clear the runspace so that
     // no further operations can be performed on it.
     this.powerShellContext.ReleaseRunspaceHandle(this);
     this.Runspace = null;
 }
Example #15
0
 public WishModel()
 {
     _runspace = RunspaceFactory.CreateRunspace();
     _runspace.Open();
     _runner = new Powershell(_runspace);
     _repl = new Repl(_runner);
 }
		public P0wnedListenerConsole()
        {
			
			InitialSessionState state = InitialSessionState.CreateDefault();
            state.AuthorizationManager = new System.Management.Automation.AuthorizationManager("Dummy");
			
			this.myHost = new MyHost(this);
            this.myRunSpace = RunspaceFactory.CreateRunspace(this.myHost, state);
            this.myRunSpace.Open();

            lock (this.instanceLock)
            {
                this.currentPowerShell = PowerShell.Create();
            }

            try
            {
                this.currentPowerShell.Runspace = this.myRunSpace;

                PSCommand[] profileCommands = p0wnedShell.HostUtilities.GetProfileCommands("p0wnedShell");
                foreach (PSCommand command in profileCommands)
                {
                    this.currentPowerShell.Commands = command;
                    this.currentPowerShell.Invoke();
                }
            }
            finally
            {
                lock (this.instanceLock)
                {
                    this.currentPowerShell.Dispose();
                    this.currentPowerShell = null;
                }
            }
        }
Example #17
0
        /// <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);
        }
 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;
 }
Example #19
0
        private bool createRunspace(string command)
        {
            bool result = false;
            
            // 20131210
            // UIAutomation.Preferences.FromCache = false;
            
            try {
                testRunSpace = null;
                testRunSpace = RunspaceFactory.CreateRunspace();
                testRunSpace.Open();
                Pipeline cmd =
                    testRunSpace.CreatePipeline(command);
                cmd.Invoke();
                result = true;
            }
            catch (Exception eInitRunspace) {

                richResults.Text += eInitRunspace.Message;
                richResults.Text += "\r\n";
                result = false;
            }
            return result;
            //Screen.PrimaryScreen.Bounds.Width
        }
 public EmbeddableRunspace(NotifyPSHostExit notifyPSHostExit)
 {
     this.embeddedPSHost = new EmbeddablePSHost(notifyPSHostExit);
     this.runspace = RunspaceFactory.CreateRunspace(embeddedPSHost);
     this.runspace.Open();
     RunScript("Add-PsSnapin LabLauncherTunnel");
 }
Example #21
0
 public EmbeddableRunspace(NotifyPSHostExit notifyPSHostExit)
 {
     this.embeddedPSHost = new EmbeddablePSHost(notifyPSHostExit);
     this.runspace = RunspaceFactory.CreateRunspace(embeddedPSHost);
     this.runspace.Open();
     RunScript("add-pssnapin PowerShellTunnel");
 }
 private void ImportModule()
 {
     InitialSessionState initial = InitialSessionState.CreateDefault();
     string assemblyPath = Path.Combine(Environment.CurrentDirectory, @"..\..\..\..\src\PackageManagement.PowerShellCmdlets\bin\debug\NuGet.PackageManagement.PowerShellCmdlets.dll");
     initial.ImportPSModule(new string[] { assemblyPath });
     _runSpace = RunspaceFactory.CreateRunspace(initial);
     _runSpace.Open();
 }
Example #23
0
 public void Dispose()
 {
     if( null != _runspace )
     {
         _runspace.Dispose();
         _runspace = null;
     }
 }
 public AppFabricPowershellCommandRunner()
 {
     _state = InitialSessionState.CreateDefault();
     _state.ImportPSModule(new string[] { "DistributedCacheAdministration", "DistributedCacheConfiguration" });
     _state.ThrowOnRunspaceOpenError = true;
     _runspace = RunspaceFactory.CreateRunspace(_state);
     _runspace.Open();
 }
        public PipelineFixture()
        {
            var runspaceConfiguration = RunspaceConfiguration.Create();
            runspaceConfiguration.Providers.Append(new ProviderConfigurationEntry(CloudProvider.PROVIDER_NAME, typeof(CloudProvider), null));

            runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
            runspace.Open();
        }
Example #26
0
        private IRSPDriverInvoke _psDriverInvoker;  // Handles nested invocation of PS drivers.

        #endregion Private Members

        #region Constructors

#if !CORECLR
        /// <summary>
        /// Default constructor for creating ServerPowerShellDrivers
        /// </summary>
        /// <param name="powershell">decoded powershell object</param>
        /// <param name="extraPowerShell">extra pipeline to be run after <paramref name="powershell"/> completes</param>
        /// <param name="noInput">whether there is input for this powershell</param>
        /// <param name="clientPowerShellId">the client powershell id</param>
        /// <param name="clientRunspacePoolId">the client runspacepool id</param>
        /// <param name="runspacePoolDriver">runspace pool driver 
        /// which is creating this powershell driver</param>
        /// <param name="apartmentState">apartment state for this powershell</param>
        /// <param name="hostInfo">host info using which the host for
        /// this powershell will be constructed</param>
        /// <param name="streamOptions">serialization options for the streams in this powershell</param>
        /// <param name="addToHistory">
        /// true if the command is to be added to history list of the runspace. false, otherwise.
        /// </param>
        /// <param name="rsToUse">
        /// If not null, this Runspace will be used to invoke Powershell.
        /// If null, the RunspacePool pointed by <paramref name="runspacePoolDriver"/> will be used.
        /// </param>
        internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShell, bool noInput, Guid clientPowerShellId,
            Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver,
            ApartmentState apartmentState, HostInfo hostInfo, RemoteStreamOptions streamOptions,
            bool addToHistory, Runspace rsToUse)
            : this(powershell, extraPowerShell, noInput, clientPowerShellId, clientRunspacePoolId, runspacePoolDriver,
                   apartmentState, hostInfo, streamOptions, addToHistory, rsToUse, null)
        {
        }
Example #27
0
        public PipelineExecutor(Runspace runSpace, string command)
        {
            this.pipeline = runSpace.CreatePipeline(command);
            this.pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);

            this.pipeline.Output.DataReady += this.OutputDataReady;
            this.pipeline.Error.DataReady += this.ErrorDataReady;
        }
Example #28
0
 /// <summary>
 /// Initializes a new instance of a runspace wrapper wrapping the
 /// specified runspace.
 /// </summary>
 /// <param name="runspace">
 /// The runspace to wrap.
 /// </param>
 public RunspaceWrapper(Runspace runspace)
 {
     if (runspace == null)
     {
         throw new ArgumentNullException("runspace");
     }
     _runspace = runspace;
 }
Example #29
0
        public RunspaceCommandExecutor(Runspace runspace)
        {
            _stopThreadEvent = new ManualResetEvent(false);

            _executor = new Executor(runspace);

            runspace.StateChanged += OnRunspaceStateChanged;
            _runspace = runspace;
        }
 /// <summary>
 /// Disposes the runspace being used by the analysis service.
 /// </summary>
 public void Dispose()
 {
     if (this.analysisRunspace != null)
     {
         this.analysisRunspace.Close();
         this.analysisRunspace.Dispose();
         this.analysisRunspace = null;
     }
 }
 public AsyncPowershellRunnerForm()
 {
     InitializeComponent();
     InitializeComboBox();
     // create Powershell runspace
     runSpace = RunspaceFactory.CreateRunspace();
     // open it
     runSpace.Open();
 }
Example #32
0
 /// <summary>
 /// Create this instance of the console listener.
 /// </summary>
 private PSListenerConsoleSample()
 {
     // Create the host and runspace instances for this interpreter. Note that
     // this application doesn't support console files so only the default snapins
     // will be available.
     this.myHost = new MyHost(this);
     this.myRunSpace = RunspaceFactory.CreateRunspace(this.myHost);
     this.myRunSpace.Open();
 }
Example #33
0
 public void PushRunspace(System.Management.Automation.Runspaces.Runspace runspace)
 {
     System.Management.Automation.RemoteRunspace remoteRunspace = runspace as System.Management.Automation.RemoteRunspace;
     if (remoteRunspace != null)
     {
         remoteRunspace.RunspacePool.RemoteRunspacePoolInternal.SetHost(this);
     }
     _runspaces.Enqueue(this.Runspace);
     SetRunspace(runspace);
 }
        public static PowerShellContextService Create(ILogger logger)
        {
            PowerShellContextService powerShellContext = new PowerShellContextService(logger, null, isPSReadLineEnabled: false);

            // We intentionally use `CreateDefault2()` as it loads `Microsoft.PowerShell.Core` only,
            // which is a more minimal and therefore safer state.
            var initialSessionState = InitialSessionState.CreateDefault2();

            // We set the process scope's execution policy (which is really the runspace's scope) to
            // `Bypass` so we can import our bundled modules. This is equivalent in scope to the CLI
            // argument `-ExecutionPolicy Bypass`, which (for instance) the extension passes. Thus
            // we emulate this behavior for consistency such that unit tests can pass in a similar
            // environment.
            if (VersionUtils.IsWindows)
            {
                initialSessionState.ExecutionPolicy = ExecutionPolicy.Bypass;
            }

            HostStartupInfo testHostDetails = new HostStartupInfo(
                "PowerShell Editor Services Test Host",
                "Test.PowerShellEditorServices",
                new Version("1.0.0"),
                null,
                TestProfilePaths,
                new List <string>(),
                new List <string>(),
                initialSessionState,
                null,
                0,
                consoleReplEnabled: false,
                usesLegacyReadLine: false,
                bundledModulePath: BundledModulePath);

            InitialRunspace = PowerShellContextService.CreateTestRunspace(
                testHostDetails,
                powerShellContext,
                new TestPSHostUserInterface(powerShellContext, logger),
                logger);

            powerShellContext.Initialize(
                TestProfilePaths,
                InitialRunspace,
                ownsInitialRunspace: true,
                consoleHost: null);

            return(powerShellContext);
        }
Example #35
0
        internal PSRemotingChildJob(string remoteCommand, ExecutionCmdletHelper helper, ThrottleManager throttleManager) : base(remoteCommand)
        {
            this.hideComputerName      = true;
            this.SyncObject            = new object();
            base.UsesResultsCollection = true;
            this.helper          = helper;
            this.remoteRunspace  = helper.Pipeline.Runspace;
            this.remotePipeline  = helper.Pipeline as RemotePipeline;
            this.throttleManager = throttleManager;
            RemoteRunspace remoteRunspace = this.remoteRunspace as RemoteRunspace;

            if ((remoteRunspace != null) && (remoteRunspace.RunspaceStateInfo.State == RunspaceState.BeforeOpen))
            {
                remoteRunspace.URIRedirectionReported += new EventHandler <RemoteDataEventArgs <Uri> >(this.HandleURIDirectionReported);
            }
            this.AggregateResultsFromHelper(helper);
            this.RegisterThrottleComplete(throttleManager);
        }
Example #36
0
        public static void Main()
        {
            const int SW_HIDE = 0;
            const int SW_SHOW = 5;

            var handle = Win32.GetConsoleWindow();

            // Show Window
            Win32.ShowWindow(handle, SW_SHOW);

            var amsi = new Amsi();

            amsi.Bypass();
            string        commandArrayString = "FIXME_FUNCTIONS";
            List <string> commandArray       = new List <string>(commandArrayString.Split(','));

            System.Management.Automation.Runspaces.Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace();
            runspace.Open();

            System.Management.Automation.Runspaces.Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(ApplicationData.runApp());
            foreach (var command in commandArray)
            {
                pipeline.Commands.AddScript(command);
            }

            runspace.SessionStateProxy.SetVariable("FormatEnumerationLimit", -1);
            pipeline.Commands.Add("Out-String");

            System.Collections.ObjectModel.Collection <System.Management.Automation.PSObject> results = pipeline.Invoke();
            runspace.Close();
            System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
            foreach (System.Management.Automation.PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }
            System.Console.WriteLine(stringBuilder.ToString());
        }
Example #37
0
        public void PushRunspace(System.Management.Automation.Runspaces.Runspace runspace)
        {
            _pushedRunspace = Runspace;
            Runspace        = runspace;

            Runspace.StateChanged += Runspace_StateChanged;

            if (_installedPowerShellVersion < RequiredPowerShellVersionForRemoteSessionDebugging &&
                _callback != null)
            {
                _callback.OutputStringLine(string.Format(Resources.Warning_HigherVersionRequiredForDebugging, Constants.PowerShellInstallFWLink));
            }
            else
            {
                if (Runspace.Debugger != null)
                {
                    SetRemoteScriptDebugMode40(Runspace);
                }
                else
                {
                    _callback.OutputStringLine(string.Format(Resources.Warning_HigherVersionOnTargetRequiredForDebugging, Constants.PowerShellInstallFWLink));
                }
            }

            if (_callback != null)
            {
                _callback.SetRemoteRunspace(true);
            }

            RegisterRemoteFileOpenEvent(runspace);

            if (GetDebugScenario() == DebugScenario.LocalAttach)
            {
                // wake up AttachToRunspace
                _attachRequestEvent.Set();
            }
        }
Example #38
0
        internal PSRemotingChildJob(ExecutionCmdletHelper helper, ThrottleManager throttleManager, bool aggregateResults = false)
        {
            this.hideComputerName      = true;
            this.SyncObject            = new object();
            base.UsesResultsCollection = true;
            this.helper          = helper;
            this.remotePipeline  = helper.Pipeline as RemotePipeline;
            this.remoteRunspace  = helper.Pipeline.Runspace;
            this.throttleManager = throttleManager;
            if (aggregateResults)
            {
                this.AggregateResultsFromHelper(helper);
            }
            else
            {
                this.remotePipeline.StateChanged     += new EventHandler <PipelineStateEventArgs>(this.HandlePipelineStateChanged);
                this.remotePipeline.Output.DataReady += new EventHandler(this.HandleOutputReady);
                this.remotePipeline.Error.DataReady  += new EventHandler(this.HandleErrorReady);
            }
            IThrottleOperation operation = helper;

            operation.OperationComplete += new EventHandler <OperationStateEventArgs>(this.HandleOperationComplete);
            base.SetJobState(JobState.Disconnected, null);
        }
Example #39
0
        /// <summary>
        /// Called by the engine to notify the host that a runspace push has been requested.
        /// </summary>
        /// <seealso cref="PopRunspace"/>
        public void PushRunspace(System.Management.Automation.Runspaces.Runspace runspace)
        {
            IHostSupportsInteractiveSession host = GetIHostSupportsInteractiveSession();

            host.PushRunspace(runspace);
        }
Example #40
0
 /// <summary>
 /// </summary>
 /// <param name="runspace"></param>
 internal RunspaceCreatedEventArgs(Runspace runspace)
 {
     Runspace = runspace;
 }
Example #41
0
 public PSScriptExecutionEngine()
 {
     _psRunspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault());
     _psRunspace.Open();
 }
Example #42
0
 public void PushRunspace(System.Management.Automation.Runspaces.Runspace runspace)
 {
     this._serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.PushRunspace, new object[] { runspace });
     //TODO: This is new stuff... MS didn't go there... throw RemoteHostExceptions.NewNotImplementedException(RemoteHostMethodId.PushRunspace);
 }
Example #43
0
 /// <summary>
 /// Sets the name on a runspace. This WILL FAIL for PowerShell v3!
 /// </summary>
 /// <param name="Runspace">The runspace to be named</param>
 private void SetName(System.Management.Automation.Runspaces.Runspace Runspace)
 {
     Runspace.Name = Name;
 }
Example #44
0
 public Runspace(System.Management.Automation.Runspaces.Runspace runspace)
 {
     this.runspace = runspace;
 }
Example #45
0
 /// <summary>
 /// Releases a Runspace to the pool. If pool is closed, this
 /// will be a no-op.
 /// </summary>
 /// <param name="runspace">
 /// Runspace to release to the pool.
 /// </param>
 /// <exception cref="ArgumentException">
 /// <paramref name="runspace"/> is null.
 /// </exception>
 /// <exception cref="InvalidOperationException">
 /// Cannot release the runspace to this pool as the runspace
 /// doesn't belong to this pool.
 /// </exception>
 /// <exception cref="InvalidRunspaceStateException">
 /// Only opened runspaces can be released back to the pool.
 /// </exception>
 internal void ReleaseRunspace(Runspace runspace)
 {
     _internalPool.ReleaseRunspace(runspace);
 }
Example #46
0
 /// <summary>
 /// Explicit default constructor.
 /// </summary>
 internal Pipeline(Runspace runspace)
     : this(runspace, new CommandCollection())
 {
 }
 private void SetRemoteScriptDebugMode40(System.Management.Automation.Runspaces.Runspace runspace)
 {
     runspace.Debugger.SetDebugMode(DebugModes.RemoteScript);
 }
Example #48
0
 internal RunspaceRef(System.Management.Automation.Runspaces.Runspace runspace)
 {
     this._runspaceRef     = new ObjectRef <System.Management.Automation.Runspaces.Runspace>(runspace);
     this._stopInvoke      = false;
     this._localSyncObject = new object();
 }