Example #1
0
 /// <summary>
 /// Adds cmdlets to the initial state.
 /// </summary>
 internal static void AddCmdlets(InitialSessionState state)
 {
     state.Commands.Add(new SessionStateCmdletEntry[] {
         new SessionStateCmdletEntry(AssertFarCommand.MyName, typeof(Commands.AssertFarCommand), Help),
         new SessionStateCmdletEntry("Find-FarFile", typeof(Commands.FindFarFileCommand), Help),
         new SessionStateCmdletEntry("Get-FarFile", typeof(Commands.GetFarFileCommand), Help),
         new SessionStateCmdletEntry("Get-FarItem", typeof(Commands.GetFarItemCommand), Help),
         new SessionStateCmdletEntry("Get-FarPath", typeof(Commands.GetFarPathCommand), Help),
         new SessionStateCmdletEntry("Invoke-FarStepper", typeof(Commands.InvokeFarStepperCommand), Help),
         new SessionStateCmdletEntry("New-FarEditor", typeof(Commands.NewFarEditorCommand), Help),
         new SessionStateCmdletEntry("New-FarFile", typeof(Commands.NewFarFileCommand), Help),
         new SessionStateCmdletEntry("New-FarItem", typeof(Commands.NewFarItemCommand), Help),
         new SessionStateCmdletEntry("New-FarList", typeof(Commands.NewFarListCommand), Help),
         new SessionStateCmdletEntry("New-FarMenu", typeof(Commands.NewFarMenuCommand), Help),
         new SessionStateCmdletEntry("New-FarViewer", typeof(Commands.NewFarViewerCommand), Help),
         new SessionStateCmdletEntry("Open-FarEditor", typeof(Commands.OpenFarEditorCommand), Help),
         new SessionStateCmdletEntry("Open-FarPanel", typeof(Commands.OpenFarPanelCommand), Help),
         new SessionStateCmdletEntry("Open-FarViewer", typeof(Commands.OpenFarViewerCommand), Help),
         new SessionStateCmdletEntry("Out-FarList", typeof(Commands.OutFarListCommand), Help),
         new SessionStateCmdletEntry("Out-FarPanel", typeof(Commands.OutFarPanelCommand), Help),
         new SessionStateCmdletEntry("Search-FarFile", typeof(Commands.SearchFarFileCommand), Help),
         new SessionStateCmdletEntry("Show-FarMessage", typeof(Commands.ShowFarMessageCommand), Help),
         new SessionStateCmdletEntry("Start-FarJob", typeof(Commands.StartFarJobCommand), Help)
     });
 }
 public InvokeParallelTests()
 {
     _iss = CreateInitialSessionState();
     m_runspacePool = RunspaceFactory.CreateRunspacePool(_iss);
     m_runspacePool.SetMaxRunspaces(10);
     m_runspacePool.Open();
 }
Example #3
0
        /// <summary>
        /// The principal constructor that most hosts will use when creating
        /// an instance of the automation engine. It allows you to pass in an
        /// instance of PSHost that provides the host-specific I/O routines, etc.
        /// </summary>
        internal AutomationEngine(PSHost hostInterface, RunspaceConfiguration runspaceConfiguration, InitialSessionState iss)
        {
#if !CORECLR// There is no control panel items in CSS
            // Update the env variable PathEXT to contain .CPL
            var pathext = Environment.GetEnvironmentVariable("PathEXT");
            pathext = pathext ?? string.Empty;
            bool cplExist = false;
            if (pathext != string.Empty)
            {
                string[] entries = pathext.Split(Utils.Separators.Semicolon);
                foreach (string entry in entries)
                {
                    string ext = entry.Trim();
                    if (ext.Equals(".CPL", StringComparison.OrdinalIgnoreCase))
                    {
                        cplExist = true;
                        break;
                    }
                }
            }
            if (!cplExist)
            {
                pathext = (pathext == string.Empty) ? ".CPL" :
                    pathext.EndsWith(";", StringComparison.OrdinalIgnoreCase)
                    ? (pathext + ".CPL") : (pathext + ";.CPL");
                Environment.SetEnvironmentVariable("PathEXT", pathext);
            }
#endif
            if (runspaceConfiguration != null)
            {
                Context = new ExecutionContext(this, hostInterface, runspaceConfiguration);
            }
            else
            {
                Context = new ExecutionContext(this, hostInterface, iss);
            }

            EngineParser = new Language.Parser();
            CommandDiscovery = new CommandDiscovery(Context);

            // Initialize providers before loading types so that any ScriptBlocks in the
            // types.ps1xml file can be parsed.

            // Bind the execution context with RunspaceConfiguration. 
            // This has the side effect of initializing cmdlet cache and providers from runspace configuration.
            if (runspaceConfiguration != null)
            {
                runspaceConfiguration.Bind(Context);
            }
            else
            {
                // Load the iss, resetting everything to it's defaults...
                iss.Bind(Context, /*updateOnly*/ false);
            }

            InitialSessionState.SetSessionStateDrive(Context, true);

            InitialSessionState.CreateQuestionVariable(Context);
        }
 public AppFabricPowershellCommandRunner()
 {
     _state = InitialSessionState.CreateDefault();
     _state.ImportPSModule(new string[] { "DistributedCacheAdministration", "DistributedCacheConfiguration" });
     _state.ThrowOnRunspaceOpenError = true;
     _runspace = RunspaceFactory.CreateRunspace(_state);
     _runspace.Open();
 }
 public PowerShellPoolMember(PowershellPool pool, int index, InitialSessionState initialSessionState)
 {
     _pool = pool;
     _index = index;
     _initialSessionState = initialSessionState;
     _poolStreams = _pool.Streams;
     _input.Complete();
     CreatePowerShell(initialSessionState);
 }
Example #6
0
 public static Runspace CreateRunspace(InitialSessionState initialSessionState)
 {
     if (initialSessionState == null)
     {
         throw PSTraceSource.NewArgumentNullException("initialSessionState");
     }
     PSHost host = new DefaultHost(Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture);
     return CreateRunspace(host, initialSessionState);
 }
Example #7
0
 internal ExecutionContext(AutomationEngine engine, PSHost hostInterface, System.Management.Automation.Runspaces.InitialSessionState initialSessionState)
 {
     this.ignoreScriptDebug          = true;
     this.logContextCache            = new System.Management.Automation.LogContextCache();
     this._questionMarkVariableValue = true;
     this._initialSessionState       = initialSessionState;
     this._authorizationManager      = initialSessionState.AuthorizationManager;
     this.InitializeCommon(engine, hostInterface);
 }
 Runspace GetWPFCurrentThreadRunspace(InitialSessionState sessionState)
 {
     InitialSessionState clone = sessionState.Clone();
     clone.ThreadOptions = PSThreadOptions.UseCurrentThread;
     SessionStateVariableEntry window = new SessionStateVariableEntry("Window", JobWindow, "");
     SessionStateVariableEntry namedControls = new SessionStateVariableEntry("NamedControls", this.namedControls, "");
     clone.Variables.Add(window);
     clone.Variables.Add(namedControls);
     return RunspaceFactory.CreateRunspace(clone);
 }
Example #9
0
        public Runner(string id)
        {
            _id = id;
            _state = InitialSessionState.CreateDefault();
            _state.AuthorizationManager = null;

            _host = new CustomPSHost();

            _runspace = RunspaceFactory.CreateRunspace(_host, _state);
            _runspace.Open();
        }
Example #10
0
        private Harness()
        {

            this.host = new CustomPSHost(this);
            this.state = InitialSessionState.CreateDefault();
            this.state.AuthorizationManager = null;
            this.myRunSpace = RunspaceFactory.CreateRunspace(this.host, this.state);
            this.myRunSpace.ThreadOptions = PSThreadOptions.UseCurrentThread;
            this.myRunSpace.Open();

        }
Example #11
0
 public static Runspace CreateRunspace(PSHost host, InitialSessionState initialSessionState)
 {
     if (host == null)
     {
         throw PSTraceSource.NewArgumentNullException("host");
     }
     if (initialSessionState == null)
     {
         throw PSTraceSource.NewArgumentNullException("initialSessionState");
     }
     return new LocalRunspace(host, initialSessionState);
 }
Example #12
0
 internal LocalRunspace(PSHost host, RunspaceConfiguration configuration, InitialSessionState initialSessionState)
 {
     DefaultRunspace = this;
     PSHost = host;
     if (configuration == null)
         _runspaceConfiguration = RunspaceFactory.DefaultRunspaceConfiguration;
     else
         _runspaceConfiguration = configuration;
     ExecutionContext = new ExecutionContext(host, configuration);
     ExecutionContext.CurrentRunspace = this;
     _initialSessionState = initialSessionState;
 }
 public PowershellEnvironment(params PowershellModule[] modules)
 {
     initialSessionState = InitialSessionState.CreateDefault();
     string[] moduleFullPath=new string[modules.Length];
     for(int i=0;i<modules.Length;i++)
     {
         moduleFullPath[i] = modules[i].FullPath;
         initialSessionState.Assemblies.Add(new SessionStateAssemblyEntry(modules[i].FullPath));
     }
     initialSessionState.ImportPSModule(moduleFullPath);
     
     runspace = RunspaceFactory.CreateRunspace(initialSessionState);
 }
Example #14
0
        public PowershellPool(int poolSize, InitialSessionState initialSessionState, CancellationToken cancellationToken)
        {
            _poolMembers= new List<PowerShellPoolMember>(poolSize);
            _initialSessionState = initialSessionState;
            _cancellationToken = cancellationToken;

            for (var i = 0; i < poolSize; i++)
            {
                var powerShellPoolMember = new PowerShellPoolMember(this, i+1, initialSessionState);
                _poolMembers.Add(powerShellPoolMember);
                _availablePoolMembers.Add(powerShellPoolMember);
            }
        }
        internal void AddSessionStateEntry(InitialSessionState initialSessionState, SessionStateWorkflowEntry entry)
        {
            var converterInstance = Utils.GetAstToWorkflowConverterAndEnsureWorkflowModuleLoaded(null);

            var workflowInfo = entry.WorkflowInfo ??
                               converterInstance.CompileWorkflow(entry.Name, entry.Definition, initialSessionState);

            WorkflowInfo wf = new WorkflowInfo(workflowInfo);

            wf = this.SetWorkflowRaw(wf, CommandOrigin.Internal);
            wf.Visibility = entry.Visibility;
            wf.Module = entry.Module;
        }
 public virtual void Dispose(bool disposing)
 {
     if (!this.isDisposed)
     {
         if (disposing)
         {
             this.Close();
             this.cleanupTimer.Dispose();
             this._initialSessionState = null;
             this.host = null;
         }
         this.isDisposed = true;
     }
 }
Example #17
0
 internal LocalRunspace(PSHost host, RunspaceConfiguration configuration, InitialSessionState initialSessionState)
 {
     //TODO: we should support both RunspaceConfigurations and IntialSessionStates properly
     _runningPipelines = new List<Pipeline>();
     DefaultRunspace = this;
     PSHost = host;
     if (configuration == null)
         _runspaceConfiguration = RunspaceFactory.DefaultRunspaceConfiguration;
     else
         _runspaceConfiguration = configuration;
     ExecutionContext = new ExecutionContext(host, configuration);
     ExecutionContext.CurrentRunspace = this;
     _initialSessionState = initialSessionState;
 }
 public RunspacePoolInternal(int minRunspaces, int maxRunspaces, System.Management.Automation.Runspaces.InitialSessionState initialSessionState, PSHost host) : this(minRunspaces, maxRunspaces)
 {
     if (initialSessionState == null)
     {
         throw PSTraceSource.NewArgumentNullException("initialSessionState");
     }
     if (host == null)
     {
         throw PSTraceSource.NewArgumentNullException("host");
     }
     this._initialSessionState = initialSessionState.Clone();
     this.apartmentState       = initialSessionState.ApartmentState;
     this.threadOptions        = initialSessionState.ThreadOptions;
     this.host = host;
     this.pool = new Stack <Runspace>();
     this.runspaceRequestQueue = new Queue <GetRunspaceAsyncResult>();
     this.ultimateRequestQueue = new Queue <GetRunspaceAsyncResult>();
 }
        protected void OpenRunspace()
        {
            HostedSolutionLog.LogStart("OpenRunspace");

            if (session == null)
            {
                session = InitialSessionState.CreateDefault();
                session.ImportPSModule(new[] {"Hyper-V"});
            }

            Runspace runSpace = RunspaceFactory.CreateRunspace(session);
            runSpace.Open();
            runSpace.SessionStateProxy.SetVariable("ConfirmPreference", "none");

            RunSpace = runSpace;
   
            HostedSolutionLog.LogEnd("OpenRunspace");
        }
Example #20
0
 internal ServerRunspacePoolDriver(Guid clientRunspacePoolId, int minRunspaces, int maxRunspaces, PSThreadOptions threadOptions, ApartmentState apartmentState, HostInfo hostInfo, InitialSessionState initialSessionState, PSPrimitiveDictionary applicationPrivateData, ConfigurationDataFromXML configData, AbstractServerSessionTransportManager transportManager, bool isAdministrator, RemoteSessionCapability serverCapability, Hashtable configHash)
 {
     this.serverCapability = serverCapability;
     System.Management.Automation.Remoting.ServerRemoteHost host = new System.Management.Automation.Remoting.ServerRemoteHost(clientRunspacePoolId, Guid.Empty, hostInfo, transportManager);
     this.remoteHost = host;
     this.configData = configData;
     this.configHash = configHash;
     this.applicationPrivateData = applicationPrivateData;
     this.localRunspacePool = RunspaceFactory.CreateRunspacePool(minRunspaces, maxRunspaces, initialSessionState, host);
     PSThreadOptions options = configData.ShellThreadOptions.HasValue ? configData.ShellThreadOptions.Value : PSThreadOptions.UseCurrentThread;
     if ((threadOptions == PSThreadOptions.Default) || (threadOptions == options))
     {
         this.localRunspacePool.ThreadOptions = options;
     }
     else
     {
         if (!isAdministrator)
         {
             throw new InvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.MustBeAdminToOverrideThreadOptions, new object[0]));
         }
         this.localRunspacePool.ThreadOptions = threadOptions;
     }
     ApartmentState state = configData.ShellThreadApartmentState.HasValue ? configData.ShellThreadApartmentState.Value : ApartmentState.Unknown;
     if ((apartmentState == ApartmentState.Unknown) || (apartmentState == state))
     {
         this.localRunspacePool.ApartmentState = state;
     }
     else
     {
         this.localRunspacePool.ApartmentState = apartmentState;
     }
     this.clientRunspacePoolId = clientRunspacePoolId;
     this.dsHandler = new ServerRunspacePoolDataStructureHandler(this, transportManager);
     this.localRunspacePool.StateChanged += new EventHandler<RunspacePoolStateChangedEventArgs>(this.HandleRunspacePoolStateChanged);
     this.localRunspacePool.ForwardEvent += new EventHandler<PSEventArgs>(this.HandleRunspacePoolForwardEvent);
     this.localRunspacePool.RunspaceCreated += new EventHandler<RunspaceCreatedEventArgs>(this.HandleRunspaceCreated);
     this.localRunspacePool.RunspaceCreated += new EventHandler<RunspaceCreatedEventArgs>(this.HandleRunspaceCreatedForTypeTable);
     this.dsHandler.CreateAndInvokePowerShell += new EventHandler<RemoteDataEventArgs<RemoteDataObject<PSObject>>>(this.HandleCreateAndInvokePowerShell);
     this.dsHandler.GetCommandMetadata += new EventHandler<RemoteDataEventArgs<RemoteDataObject<PSObject>>>(this.HandleGetCommandMetadata);
     this.dsHandler.HostResponseReceived += new EventHandler<RemoteDataEventArgs<RemoteHostResponse>>(this.HandleHostResponseReceived);
     this.dsHandler.SetMaxRunspacesReceived += new EventHandler<RemoteDataEventArgs<PSObject>>(this.HandleSetMaxRunspacesReceived);
     this.dsHandler.SetMinRunspacesReceived += new EventHandler<RemoteDataEventArgs<PSObject>>(this.HandleSetMinRunspacesReceived);
     this.dsHandler.GetAvailableRunspacesReceived += new EventHandler<RemoteDataEventArgs<PSObject>>(this.HandleGetAvailalbeRunspacesReceived);
 }
Example #21
0
		public PSRunspace(InitialSessionState initialSessionState, bool executeCmdletInSameThread = false)
		{
			try
			{
				this.Runspace = RunspaceFactory.CreateRunspace(initialSessionState);
				if (executeCmdletInSameThread)
				{
					this.Runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;
				}
				this.Runspace.Open();
				DataServiceController.Current.PerfCounters.ActiveRunspaces.Increment();
			}
			catch (Exception exception1)
			{
				Exception exception = exception1;
				TraceHelper.Current.FailedToCreateRunspace(exception.ToTraceMessage("Exception"));
				throw new InvalidOperationException(ExceptionHelpers.GetExceptionMessage(exception, Resources.PowerShellConstrainedRunspaceCreationFailed, new object[0]), exception);
			}
		}
Example #22
0
        protected RunspaceBase(PSHost host, InitialSessionState initialSessionState)
        {
            if (host == null)
            {
                throw PSTraceSource.NewArgumentNullException("host");
            }
            if (initialSessionState == null)
            {
                throw PSTraceSource.NewArgumentNullException("initialSessionState");
            }

            Host = host;
            InitialSessionState = initialSessionState.Clone();
            this.ThreadOptions = initialSessionState.ThreadOptions;

#if !CORECLR // No ApartmentState In CoreCLR
            this.ApartmentState = initialSessionState.ApartmentState;
#endif
        }
Example #23
0
 internal AutomationEngine(PSHost hostInterface, RunspaceConfiguration runspaceConfiguration, InitialSessionState iss)
 {
     string str = Environment.GetEnvironmentVariable("PathEXT") ?? string.Empty;
     bool flag = false;
     if (str != string.Empty)
     {
         foreach (string str2 in str.Split(new char[] { ';' }))
         {
             if (str2.Trim().Equals(".CPL", StringComparison.OrdinalIgnoreCase))
             {
                 flag = true;
                 break;
             }
         }
     }
     if (!flag)
     {
         str = (str == string.Empty) ? ".CPL" : (str.EndsWith(";", StringComparison.OrdinalIgnoreCase) ? (str + ".CPL") : (str + ";.CPL"));
         Environment.SetEnvironmentVariable("PathEXT", str);
     }
     if (runspaceConfiguration != null)
     {
         this._context = new ExecutionContext(this, hostInterface, runspaceConfiguration);
     }
     else
     {
         this._context = new ExecutionContext(this, hostInterface, iss);
     }
     this.EngineNewParser = new Parser();
     this.commandDiscovery = new System.Management.Automation.CommandDiscovery(this._context);
     if (runspaceConfiguration != null)
     {
         runspaceConfiguration.Bind(this._context);
     }
     else
     {
         iss.Bind(this._context, false);
     }
     InitialSessionState.SetSessionStateDrive(this._context, true);
     InitialSessionState.CreateQuestionVariable(this._context);
 }
Example #24
0
 public static Runspace CreateRunspace(InitialSessionState initialSessionState)
 {
     PSHost host = new LocalHost(); // DefaultHost(Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture);
     return RunspaceFactory.CreateRunspace(host, initialSessionState);
 }
Example #25
0
 public static Runspace CreateRunspace(PSHost host, InitialSessionState initialSessionState)
 {
     return new LocalRunspace(host, initialSessionState);
 }
		static PSWorkflowSessionConfiguration()
		{
			PSWorkflowSessionConfiguration.InitialSessionState = InitialSessionState.CreateRestricted(SessionCapabilities.RemoteServer | SessionCapabilities.WorkflowServer | SessionCapabilities.Language);
			PSWorkflowSessionConfiguration._modulesLoaded = 0;
		}
		private static void CaptureVariables(SessionState sessionState, InitialSessionState initialSessionState)
		{
			var variables = GetVariables(sessionState);
			foreach (var variable in variables)
			{
				var existing = initialSessionState.Variables[variable.Name].FirstOrDefault();
				if (existing != null)
				{
					if ((existing.Options & (ScopedItemOptions.Constant | ScopedItemOptions.ReadOnly)) != ScopedItemOptions.None)
					{
						continue;
					}
					else
					{
						initialSessionState.Variables.Remove(existing.Name, existing.GetType());
						initialSessionState.Variables.Add(new SessionStateVariableEntry(variable.Name, variable.Value, variable.Description, variable.Options, variable.Attributes));
					}
				}
				else
				{
					initialSessionState.Variables.Add(new SessionStateVariableEntry(variable.Name, variable.Value, variable.Description, variable.Options, variable.Attributes));
				}
			}
		}
		private static void CaptureFunctions(SessionState sessionState, InitialSessionState initialSessionState)
		{
			var functions = GetFunctions(sessionState);
			foreach (var func in functions)
			{
				initialSessionState.Commands.Add(new SessionStateFunctionEntry(func.Name, func.Definition));
			}
		}
Example #29
0
 public RunspacePoolInternal(int minRunspaces, int maxRunspaces, System.Management.Automation.Runspaces.InitialSessionState initialSessionState, PSHost host) : this(minRunspaces, maxRunspaces)
 {
     if (initialSessionState == null)
     {
         throw PSTraceSource.NewArgumentNullException("initialSessionState");
     }
     if (host == null)
     {
         throw PSTraceSource.NewArgumentNullException("host");
     }
     this._initialSessionState = initialSessionState.Clone();
     this.apartmentState = initialSessionState.ApartmentState;
     this.threadOptions = initialSessionState.ThreadOptions;
     this.host = host;
     this.pool = new Stack<Runspace>();
     this.runspaceRequestQueue = new Queue<GetRunspaceAsyncResult>();
     this.ultimateRequestQueue = new Queue<GetRunspaceAsyncResult>();
 }
Example #30
0
 public virtual void Dispose(bool disposing)
 {
     if (!this.isDisposed)
     {
         if (disposing)
         {
             this.Close();
             this.cleanupTimer.Dispose();
             this._initialSessionState = null;
             this.host = null;
         }
         this.isDisposed = true;
     }
 }
Example #31
0
 public static RunspacePool CreateRunspacePool(int minRunspaces, int maxRunspaces,
     InitialSessionState initialSessionState, PSHost host)
 {
     return new RunspacePool(minRunspaces,
         maxRunspaces, initialSessionState, host);
 }
Example #32
0
 public static RunspacePool CreateRunspacePool(InitialSessionState initialSessionState)
 {
     return CreateRunspacePool(1, 1, initialSessionState,
         new DefaultHost
         (
             CultureInfo.CurrentCulture,
             CultureInfo.CurrentUICulture
         ));
 }
Example #33
0
 internal LocalRunspace(PSHost host, InitialSessionState initialSessionState)
     : base(host, initialSessionState)
 {
 }