internal virtual Runspace OpenRunspace()
        {
            HostedSolutionLog.LogStart("OpenRunspace");

            if (runspaceConfiguration == null)
            {
                runspaceConfiguration = RunspaceConfiguration.Create();
                PSSnapInException exception = null;

                PSSnapInInfo info = runspaceConfiguration.AddPSSnapIn(SharepointSnapInName, out exception);
                HostedSolutionLog.LogInfo("Sharepoint snapin loaded");

                if (exception != null)
                {
                    HostedSolutionLog.LogWarning("SnapIn error", exception);
                }
            }
            Runspace runSpace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
            //
            runSpace.Open();
            //
            runSpace.SessionStateProxy.SetVariable("ConfirmPreference", "none");
            HostedSolutionLog.LogEnd("OpenRunspace");
            return runSpace;
        }
      /// <summary>
      /// Default Constructor copies all the data from the "default" RunspaceConfiguration
      /// </summary>
      public PoshRunspaceConfiguration()
      {
         _baseConfig = RunspaceConfiguration.Create();
         // AuthorizationManager = baseConfig.AuthorizationManager;
         // ToDo: Add the HuddledControls assembly to the Assemeblies 
         Assemblies.Append(_baseConfig.Assemblies);
         Cmdlets.Append(_baseConfig.Cmdlets);
         Formats.Append(_baseConfig.Formats);
         InitializationScripts.Append(_baseConfig.InitializationScripts);
         Providers.Append(_baseConfig.Providers);
         Scripts.Append(_baseConfig.Scripts);
         Types.Append(_baseConfig.Types);

         // TODO: uncomment this if we start really using it
         //foreach (var t in System.Reflection.Assembly.GetEntryAssembly().GetTypes())
         //{
         //   var cmdlets = t.GetCustomAttributes(typeof(System.Management.Automation.CmdletAttribute), false) as System.Management.Automation.CmdletAttribute[];
         //   if (cmdlets != null)
         //   {
         //      foreach (var cmdlet in cmdlets)
         //      {
         //         Cmdlets.Append(new CmdletConfigurationEntry(
         //                           string.Format("{0}-{1}", cmdlet.VerbName, cmdlet.NounName), t,
         //                           string.Format("{0}.xml", t.Name)));
         //      }
         //   }
         //}

      }
        private static string GetAndCheckFullFileName(
            string psSnapinName,
            Hashtable fullFileNameHash,
            RunspaceConfiguration runspaceConfiguration,
            string baseFolder,
            string baseFileName,
            Collection <string> independentErrors)
        {
            string path = !Path.IsPathRooted(baseFileName) ? Path.Combine(baseFolder, baseFileName) : baseFileName;

            if (!File.Exists(path))
            {
                string str = ResourceManagerCache.FormatResourceString("TypesXml", "FileNotFound", (object)psSnapinName, (object)path);
                independentErrors.Add(str);
                return((string)null);
            }
            string str1 = (string)fullFileNameHash[(object)path];

            if (str1 != null)
            {
                string str2 = ResourceManagerCache.FormatResourceString("TypesXml", "DuplicateFile", (object)psSnapinName, (object)path, (object)str1);
                independentErrors.Add(str2);
                return((string)null);
            }
            if (!path.EndsWith(".ps1xml", StringComparison.OrdinalIgnoreCase))
            {
                string str2 = ResourceManagerCache.FormatResourceString("TypesXml", "EntryShouldBeMshXml", (object)psSnapinName, (object)path);
                independentErrors.Add(str2);
                return((string)null);
            }
            fullFileNameHash.Add((object)path, (object)psSnapinName);
            return(path);
        }
Beispiel #4
0
        internal static Collection <PSSnapInTypeAndFormatErrors> GetFormatAndTypesErrors(
            RunspaceConfiguration runspaceConfiguration,
            PSHost host,
            IEnumerable <RunspaceConfigurationEntry> configurationEntryCollection,
            Collection <string> independentErrors,
            Collection <int> entryIndicesToRemove)
        {
            Collection <PSSnapInTypeAndFormatErrors> returnValue = new Collection <PSSnapInTypeAndFormatErrors>();

            string baseFolder = GetBaseFolder(runspaceConfiguration, independentErrors);
            var    psHome     = Utils.GetApplicationBase(Utils.DefaultPowerShellShellID);

            // this hashtable will be used to check whether this is duplicated file for types or formats.
            HashSet <string> fullFileNameSet = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
            int index = -1;

            foreach (var configurationEntry in configurationEntryCollection)
            {
                string fileName;
                string psSnapinName = configurationEntry.PSSnapIn == null ? runspaceConfiguration.ShellId : configurationEntry.PSSnapIn.Name;
                index++;
                var typeEntry = configurationEntry as TypeConfigurationEntry;
                if (typeEntry != null)
                {
                    fileName = typeEntry.FileName;

                    if (fileName == null)
                    {
                        returnValue.Add(new PSSnapInTypeAndFormatErrors(psSnapinName, typeEntry.TypeData, typeEntry.IsRemove));
                        continue;
                    }
                }
                else
                {
                    FormatConfigurationEntry formatEntry = (FormatConfigurationEntry)configurationEntry;
                    fileName = formatEntry.FileName;

                    if (fileName == null)
                    {
                        returnValue.Add(new PSSnapInTypeAndFormatErrors(psSnapinName, formatEntry.FormatData));
                        continue;
                    }
                }

                bool   checkFileExists   = configurationEntry.PSSnapIn == null || string.Equals(psHome, configurationEntry.PSSnapIn.AbsoluteModulePath, StringComparison.OrdinalIgnoreCase);
                bool   needToRemoveEntry = false;
                string fullFileName      = GetAndCheckFullFileName(psSnapinName, fullFileNameSet, baseFolder, fileName, independentErrors, ref needToRemoveEntry, checkFileExists);
                if (fullFileName == null)
                {
                    if (needToRemoveEntry)
                    {
                        entryIndicesToRemove.Add(index);
                    }
                    continue;
                }

                returnValue.Add(new PSSnapInTypeAndFormatErrors(psSnapinName, fullFileName));
            }
            return(returnValue);
        }
Beispiel #5
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);
        }
Beispiel #6
0
 public ExecutionContext(PSHost host, RunspaceConfiguration config)
     : this()
 {
     RunspaceConfiguration = config;
     LocalHost = host;
     SessionStateGlobal = new SessionStateGlobal(this);
     SessionState = new SessionState(SessionStateGlobal);
 }
Beispiel #7
0
 public static Runspace CreateRunspace(PSHost host)
 {
     if (host == null)
     {
         throw PSTraceSource.NewArgumentNullException("host");
     }
     return(CreateRunspace(host, RunspaceConfiguration.Create()));
 }
Beispiel #8
0
 /// <summary>
 ///     Initializes a new instance of the MyHost class. Keep
 ///     a reference to the host application object so that it
 ///     can be informed of when to exit.
 /// </summary>
 public ScriptingHost(ApplicationSettings settings, RunspaceConfiguration runspaceConfiguration)
 {
     this.runspaceConfiguration = runspaceConfiguration;
     ui = new ScriptingHostUserInterface(settings);
     pushedRunspaces = new Stack<Runspace>();
     privateData = new ScriptingHostPrivateData(this);
     CloseRunner = false;
 }
Beispiel #9
0
 public static Runspace CreateRunspace(RunspaceConfiguration runspaceConfiguration)
 {
     if (runspaceConfiguration == null)
     {
         throw RunspaceFactory._tracer.NewArgumentNullException(nameof(runspaceConfiguration));
     }
     return(RunspaceFactory.CreateRunspace((PSHost) new DefaultHost(Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture), runspaceConfiguration));
 }
Beispiel #10
0
 // TODO: make sure to implement a Singleton DefaultRunspace pattern
 //internal static LocalRunspace DefaultRunspace { get; private set; }
 public LocalRunspace(PSHost host, RunspaceConfiguration configuration)
 {
     DefaultRunspace = this;
     PSHost = host;
     _runspaceConfiguration = configuration;
     ExecutionContext = new ExecutionContext(host, configuration);
     ExecutionContext.CurrentRunspace = this;
 }
Beispiel #11
0
 public static Runspace CreateRunspace(RunspaceConfiguration runspaceConfiguration)
 {
     if (runspaceConfiguration == null)
     {
         throw PSTraceSource.NewArgumentNullException("runspaceConfiguration");
     }
     PSHost host = new DefaultHost(Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture);
     return CreateRunspace(host, runspaceConfiguration);
 }
Beispiel #12
0
 internal RunspacePool(
     int minRunspaces,
     int maxRunspaces,
     RunspaceConfiguration runspaceConfiguration,
     PSHost host)
 {
     using (RunspacePool.tracer.TraceConstructor((object)this))
         this.internalPool = new RunspacePoolInternal(minRunspaces, maxRunspaces, runspaceConfiguration, host);
 }
Beispiel #13
0
 private static RunspacePool CreateRunspacePool(
     int minRunspaces,
     int maxRunspaces,
     RunspaceConfiguration runspaceConfiguration,
     PSHost host)
 {
     using (RunspaceFactory._tracer.TraceMethod())
         return(new RunspacePool(minRunspaces, maxRunspaces, runspaceConfiguration, host));
 }
Beispiel #14
0
 internal ExecutionContext(AutomationEngine engine, PSHost hostInterface, System.Management.Automation.Runspaces.RunspaceConfiguration runspaceConfiguration)
 {
     this.ignoreScriptDebug          = true;
     this.logContextCache            = new System.Management.Automation.LogContextCache();
     this._questionMarkVariableValue = true;
     this._runspaceConfiguration     = runspaceConfiguration;
     this._authorizationManager      = runspaceConfiguration.AuthorizationManager;
     this.InitializeCommon(engine, hostInterface);
 }
Beispiel #15
0
 public Host(string name, Version version, PSHostUserInterface hostUI,
             RunspaceConfiguration runspaceConfiguration)
 {
     _pushedRunspaces = new Stack<Runspace>();
     _name = name;
     _version = version;
     _hostUI = hostUI;
     _runspaceConfiguration = runspaceConfiguration;
     _exitEvent = new ManualResetEvent(false);
 }
Beispiel #16
0
        /// <summary>
        /// Constructor which creates a RunspacePool using the
        /// supplied <paramref name="configuration"/>,
        /// <paramref name="minRunspaces"/> and <paramref name="maxRunspaces"/>
        /// </summary>
        /// <param name="minRunspaces">
        /// The minimum number of Runspaces that can exist in this pool.
        /// Should be greater than or equal to 1.
        /// </param>
        /// <param name="maxRunspaces">
        /// The maximum number of Runspaces that can exist in this pool.
        /// Should be greater than or equal to 1.
        /// </param>
        /// <param name="runspaceConfiguration">
        /// RunspaceConfiguration to use when creating a new Runspace.
        /// </param>
        /// <param name="host">
        /// The explicit PSHost implementation.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// RunspaceConfiguration is null.
        /// Host is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// Maximum runspaces is less than 1.
        /// Minimum runspaces is less than 1.
        /// </exception>
        internal RunspacePool(int minRunspaces, int maxRunspaces,
                              RunspaceConfiguration runspaceConfiguration, PSHost host)
        {
            // Currently we support only Local Runspace Pool..
            // this needs to be changed once remote runspace pool
            // is implemented

            _internalPool = new RunspacePoolInternal(minRunspaces,
                                                     maxRunspaces, runspaceConfiguration, host);
        }
Beispiel #17
0
 /// <summary>
 /// Creates a RunspacePool using default RunspaceConfiguration
 /// with MaxRunspaces 1 and MinRunspaces 1.
 /// </summary>
 public static RunspacePool CreateRunspacePool()
 {
     return(CreateRunspacePool(1, 1,
                               RunspaceConfiguration.Create(),
                               new DefaultHost
                               (
                                   CultureInfo.CurrentCulture,
                                   CultureInfo.CurrentUICulture
                               )));
 }
Beispiel #18
0
        public static Runspace CreateRunspace(RunspaceConfiguration runspaceConfiguration)
        {
            if (runspaceConfiguration == null)
            {
                throw PSTraceSource.NewArgumentNullException("runspaceConfiguration");
            }
            PSHost host = new DefaultHost(Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture);

            return(CreateRunspace(host, runspaceConfiguration));
        }
Beispiel #19
0
 /// <summary>
 /// Creates a RunspacePool using default RunspaceConfiguration.
 /// <paramref name="maxRunspaces"/>
 /// limits the number of Runspaces that can exist in this
 /// pool. The minimum pool size is set to <paramref name="minPoolSoze"/>.
 /// </summary>
 /// <param name="minRunspaces">
 /// The minimum number of Runspaces that exist in this
 /// pool. Should be greater than or equal to 1.
 /// </param>
 /// <param name="maxRunspaces">
 /// The maximum number of Runspaces that can exist in this
 /// pool. Should be greater than or equal to 1.
 /// </param>
 /// <exception cref="ArgumentException">
 /// Maximum runspaces is less than 1.
 /// Minimum runspaces is less than 1.
 /// </exception>
 public static RunspacePool CreateRunspacePool(int minRunspaces, int maxRunspaces)
 {
     return(CreateRunspacePool(minRunspaces, maxRunspaces,
                               RunspaceConfiguration.Create(),
                               new DefaultHost
                               (
                                   CultureInfo.CurrentCulture,
                                   CultureInfo.CurrentUICulture
                               )));
 }
Beispiel #20
0
 public static Runspace CreateRunspace(
     PSHost host,
     RunspaceConfiguration runspaceConfiguration)
 {
     if (host == null)
     {
         throw RunspaceFactory._tracer.NewArgumentNullException(nameof(host));
     }
     return(runspaceConfiguration != null ? (Runspace) new LocalRunspace(host, runspaceConfiguration) : throw RunspaceFactory._tracer.NewArgumentNullException(nameof(runspaceConfiguration)));
 }
Beispiel #21
0
 private void InitializeScript()
 {
     rspaceconfig = RunspaceConfiguration.Create();
     host = new psfhost(frm);
     hostinterface = (psfhostinterface)host.UI;
     hostinterface.WriteProgressUpdate += WriteProgressUpdate;
     hostinterface.WriteUpdate += WriteUpdate;
     rspace = RunspaceFactory.CreateRunspace(host, rspaceconfig);
     rspace.Open();
     InitializeSessionVars();
 }
Beispiel #22
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;
 }
Beispiel #23
0
		internal static int Start(RunspaceConfiguration configuration, string bannerText, string helpText, string preStartWarning, string[] args)
		{
			if (args != null)
			{
				ConsoleControl.UpdateLocaleSpecificFont();
				return ConsoleHost.Start(configuration, bannerText, helpText, preStartWarning, args);
			}
			else
			{
				throw PSTraceSource.NewArgumentNullException("args");
			}
		}
Beispiel #24
0
 public static Runspace CreateRunspace(PSHost host, RunspaceConfiguration runspaceConfiguration)
 {
     if (host == null)
     {
         throw PSTraceSource.NewArgumentNullException("host");
     }
     if (runspaceConfiguration == null)
     {
         throw PSTraceSource.NewArgumentNullException("runspaceConfiguration");
     }
     return(new LocalRunspace(host, runspaceConfiguration));
 }
Beispiel #25
0
 /// <summary>
 /// Creates a RunspaceInvoke for invoking commands. Underlying Runspace is created using
 /// specified RunspaceConfiguration
 /// </summary>
 /// <param name="runspaceConfiguration">RunspaceConfiguration used for creating the runspace
 /// </param>
 /// <exception cref="ArgumentNullException">
 /// Thrown when runspaceConfiguration is null
 /// </exception>    
 public RunspaceInvoke(RunspaceConfiguration runspaceConfiguration)
 {
     if (runspaceConfiguration == null)
     {
         throw PSTraceSource.NewArgumentNullException("runspaceConfiguration");
     }
     _runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
     _runspace.Open();
     if (Runspace.DefaultRunspace == null)
     {
         Runspace.DefaultRunspace = _runspace;
     }
 }
Beispiel #26
0
 protected RunspaceBase(PSHost host, RunspaceConfiguration runspaceConfiguration)
 {
     if (host == null)
     {
         throw RunspaceBase._trace.NewArgumentNullException(nameof(host));
     }
     if (runspaceConfiguration == null)
     {
         throw RunspaceBase._trace.NewArgumentNullException(nameof(runspaceConfiguration));
     }
     this._host = host;
     this._runspaceConfiguration = runspaceConfiguration;
 }
Beispiel #27
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;
 }
Beispiel #28
0
        /// <summary>
        /// Construct an instance of an Runspace using a custom 
        /// implementation of PSHost.
        /// </summary>
        /// <param name="host">The explicit PSHost implementation</param>
        /// <exception cref="System.ArgumentNullException">
        /// Host is null.
        /// </exception>
        /// <exception cref="System.ArgumentNullException">
        /// host is null.
        /// </exception>
        /// <param name="runspaceConfiguration">
        /// configuration information for this minshell.
        /// </param>
        protected RunspaceBase(PSHost host, RunspaceConfiguration runspaceConfiguration)
        {
            if (host == null)
            {
                throw PSTraceSource.NewArgumentNullException("host");
            }
            if (runspaceConfiguration == null)
            {
                throw PSTraceSource.NewArgumentNullException("runspaceConfiguration");
            }

            Host = host;
            RunspaceConfiguration = runspaceConfiguration;
        }
        internal static Collection <PSSnapInTypeAndFormatErrors> GetFormatAndTypesErrors(
            RunspaceConfiguration runspaceConfiguration,
            PSHost host,
            IEnumerable configurationEntryCollection,
            RunspaceConfigurationCategory category,
            Collection <string> independentErrors)
        {
            Collection <PSSnapInTypeAndFormatErrors> collection = new Collection <PSSnapInTypeAndFormatErrors>();
            string    baseFolder       = FormatAndTypeDataHelper.GetBaseFolder(runspaceConfiguration, independentErrors);
            Hashtable fullFileNameHash = new Hashtable((IEqualityComparer)StringComparer.OrdinalIgnoreCase);

            foreach (object configurationEntry1 in configurationEntryCollection)
            {
                string fileName;
                string str;
                if (category == RunspaceConfigurationCategory.Types)
                {
                    TypeConfigurationEntry configurationEntry2 = (TypeConfigurationEntry)configurationEntry1;
                    fileName = configurationEntry2.FileName;
                    str      = configurationEntry2.PSSnapIn == null ? runspaceConfiguration.ShellId : configurationEntry2.PSSnapIn.Name;
                }
                else
                {
                    FormatConfigurationEntry configurationEntry2 = (FormatConfigurationEntry)configurationEntry1;
                    fileName = configurationEntry2.FileName;
                    str      = configurationEntry2.PSSnapIn == null ? runspaceConfiguration.ShellId : configurationEntry2.PSSnapIn.Name;
                }
                string checkFullFileName1 = FormatAndTypeDataHelper.GetAndCheckFullFileName(str, fullFileNameHash, runspaceConfiguration, baseFolder, fileName, independentErrors);
                if (checkFullFileName1 != null)
                {
                    if (checkFullFileName1.EndsWith("filelist.ps1xml", StringComparison.OrdinalIgnoreCase))
                    {
                        foreach (string readFile in runspaceConfiguration.TypeTable.ReadFiles(str, checkFullFileName1, independentErrors, runspaceConfiguration.AuthorizationManager, host))
                        {
                            string checkFullFileName2 = FormatAndTypeDataHelper.GetAndCheckFullFileName(str, fullFileNameHash, runspaceConfiguration, baseFolder, readFile, independentErrors);
                            if (checkFullFileName2 != null)
                            {
                                collection.Add(new PSSnapInTypeAndFormatErrors(str, checkFullFileName2));
                            }
                        }
                    }
                    else
                    {
                        collection.Add(new PSSnapInTypeAndFormatErrors(str, checkFullFileName1));
                    }
                }
            }
            return(collection);
        }
 public RunspacePoolInternal(int minRunspaces, int maxRunspaces, System.Management.Automation.Runspaces.RunspaceConfiguration runspaceConfiguration, PSHost host) : this(minRunspaces, maxRunspaces)
 {
     if (runspaceConfiguration == null)
     {
         throw PSTraceSource.NewArgumentNullException("runspaceConfiguration");
     }
     if (host == null)
     {
         throw PSTraceSource.NewArgumentNullException("host");
     }
     this.rsConfig             = runspaceConfiguration;
     this.host                 = host;
     this.pool                 = new Stack <Runspace>();
     this.runspaceRequestQueue = new Queue <GetRunspaceAsyncResult>();
     this.ultimateRequestQueue = new Queue <GetRunspaceAsyncResult>();
 }
 private static string GetBaseFolder(RunspaceConfiguration runspaceConfiguration, Collection<string> independentErrors)
 {
     string shellPathFromRegistry = CommandDiscovery.GetShellPathFromRegistry(runspaceConfiguration.ShellId);
     if (shellPathFromRegistry == null)
     {
         return Path.GetDirectoryName(PsUtils.GetMainModule(Process.GetCurrentProcess()).FileName);
     }
     if (OSHelper.IsWindows) shellPathFromRegistry = Path.GetDirectoryName(shellPathFromRegistry);
     if (!Directory.Exists(shellPathFromRegistry))
     {
         string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
         string item = StringUtil.Format(TypesXmlStrings.CannotFindRegistryKeyPath, new object[] { shellPathFromRegistry, Utils.GetRegistryConfigurationPath(runspaceConfiguration.ShellId), @"\Path", directoryName });
         independentErrors.Add(item);
         shellPathFromRegistry = directoryName;
     }
     return shellPathFromRegistry;
 }
Beispiel #32
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);
 }
Beispiel #33
0
        private static RunspaceConfiguration Create(Assembly assembly)
        {
            using (RunspaceConfiguration.tracer.TraceMethod())
            {
                object[] objArray = assembly != null?assembly.GetCustomAttributes(typeof(RunspaceConfigurationTypeAttribute), false) : throw RunspaceConfiguration.tracer.NewArgumentNullException(nameof(assembly));

                if (objArray == null || objArray.Length == 0)
                {
                    throw new RunspaceConfigurationAttributeException("RunspaceConfigurationAttributeNotExist", assembly.FullName);
                }
                RunspaceConfigurationTypeAttribute configurationTypeAttribute = objArray.Length <= 1 ? (RunspaceConfigurationTypeAttribute)objArray[0] : throw new RunspaceConfigurationAttributeException("RunspaceConfigurationAttributeDuplicate", assembly.FullName);
                try
                {
                    return(RunspaceConfiguration.Create(assembly.GetType(configurationTypeAttribute.RunspaceConfigurationType, true)));
                }
                catch (SecurityException ex)
                {
                    throw new RunspaceConfigurationTypeException(assembly.FullName, configurationTypeAttribute.RunspaceConfigurationType);
                }
            }
        }
Beispiel #34
0
        private static string GetBaseFolder(RunspaceConfiguration runspaceConfiguration, Collection <string> independentErrors)
        {
            string shellPathFromRegistry = CommandDiscovery.GetShellPathFromRegistry(runspaceConfiguration.ShellId);

            if (shellPathFromRegistry == null)
            {
                return(Path.GetDirectoryName(PsUtils.GetMainModule(Process.GetCurrentProcess()).FileName));
            }
            if (OSHelper.IsWindows)
            {
                shellPathFromRegistry = Path.GetDirectoryName(shellPathFromRegistry);
            }
            if (!Directory.Exists(shellPathFromRegistry))
            {
                string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                string item          = StringUtil.Format(TypesXmlStrings.CannotFindRegistryKeyPath, new object[] { shellPathFromRegistry, Utils.GetRegistryConfigurationPath(runspaceConfiguration.ShellId), @"\Path", directoryName });
                independentErrors.Add(item);
                shellPathFromRegistry = directoryName;
            }
            return(shellPathFromRegistry);
        }
 private static string GetBaseFolder(
     RunspaceConfiguration runspaceConfiguration,
     Collection<string> independentErrors)
 {
     string returnValue = CommandDiscovery.GetShellPathFromRegistry(runspaceConfiguration.ShellId);
     if (returnValue == null)
     {
         returnValue = Path.GetDirectoryName(PsUtils.GetMainModule(System.Diagnostics.Process.GetCurrentProcess()).FileName);
     }
     else
     {
         returnValue = Path.GetDirectoryName(returnValue);
         if (!Directory.Exists(returnValue))
         {
             string newReturnValue = Path.GetDirectoryName(typeof(FormatAndTypeDataHelper).GetTypeInfo().Assembly.Location);
             string error = StringUtil.Format(TypesXmlStrings.CannotFindRegistryKeyPath, returnValue,
                 Utils.GetRegistryConfigurationPath(runspaceConfiguration.ShellId), "\\Path", newReturnValue);
             independentErrors.Add(error);
             returnValue = newReturnValue;
         }
     }
     return returnValue;
 }
Beispiel #36
0
 public static RunspaceConfiguration Create(string assemblyName)
 {
     using (RunspaceConfiguration.tracer.TraceMethod())
     {
         if (string.IsNullOrEmpty(assemblyName))
         {
             throw RunspaceConfiguration.tracer.NewArgumentNullException(nameof(assemblyName));
         }
         Assembly assembly1 = (Assembly)null;
         foreach (Assembly assembly2 in AppDomain.CurrentDomain.GetAssemblies())
         {
             if (string.Equals(assembly2.GetName().Name, assemblyName, StringComparison.OrdinalIgnoreCase))
             {
                 assembly1 = assembly2;
                 break;
             }
         }
         if (assembly1 == null)
         {
             assembly1 = Assembly.Load(assemblyName);
         }
         return(RunspaceConfiguration.Create(assembly1));
     }
 }
Beispiel #37
0
        private static string GetBaseFolder(
            RunspaceConfiguration runspaceConfiguration,
            Collection <string> independentErrors)
        {
            string returnValue = CommandDiscovery.GetShellPathFromRegistry(runspaceConfiguration.ShellId);

            if (returnValue == null)
            {
                returnValue = Path.GetDirectoryName(PsUtils.GetMainModule(System.Diagnostics.Process.GetCurrentProcess()).FileName);
            }
            else
            {
                returnValue = Path.GetDirectoryName(returnValue);
                if (!Directory.Exists(returnValue))
                {
                    string newReturnValue = Path.GetDirectoryName(typeof(FormatAndTypeDataHelper).GetTypeInfo().Assembly.Location);
                    string error          = StringUtil.Format(TypesXmlStrings.CannotFindRegistryKeyPath, returnValue,
                                                              Utils.GetRegistryConfigurationPath(runspaceConfiguration.ShellId), "\\Path", newReturnValue);
                    independentErrors.Add(error);
                    returnValue = newReturnValue;
                }
            }
            return(returnValue);
        }
Beispiel #38
0
        Start(RunspaceConfiguration configuration,
              string bannerText,
              string helpText,
              string preStartWarning,
              string[] args)
        {
            if (args == null)
            {
                throw PSTraceSource.NewArgumentNullException("args");
            }

            // The default font face used for Powershell Console is Lucida Console. 
            // However certain CJK locales dont support Lucida Console font. Hence for such 
            // locales the console font is updated to Raster dynamically.

            // For NanoServer:
            // 1. There is no GetCurrentConsoleFontEx / SetCurrentConsoleFontEx on NanoServer;
            // 2. We don't handle CJK locales on NanoServer due to lack of win32 API supports on NanoServer.
#if !CORECLR
            ConsoleControl.UpdateLocaleSpecificFont();
#endif

            return ConsoleHost.Start(configuration, bannerText, helpText, preStartWarning, args);
        }
        private static string GetBaseFolder(
            RunspaceConfiguration runspaceConfiguration,
            Collection <string> independentErrors)
        {
            string pathFromRegistry = CommandDiscovery.GetShellPathFromRegistry(runspaceConfiguration.ShellId);
            string path;

            if (pathFromRegistry == null)
            {
                path = Path.GetDirectoryName(PsUtils.GetMainModule(Process.GetCurrentProcess()).FileName);
            }
            else
            {
                path = Path.GetDirectoryName(pathFromRegistry);
                if (!Directory.Exists(path))
                {
                    string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                    string str           = ResourceManagerCache.FormatResourceString("TypesXml", "CannotFindRegistryKeyPath", (object)path, (object)Utils.GetRegistryConfigurationPath(runspaceConfiguration.ShellId), (object)"\\Path", (object)directoryName);
                    independentErrors.Add(str);
                    path = directoryName;
                }
            }
            return(path);
        }
Beispiel #40
0
 public static Runspace CreateRunspace(RunspaceConfiguration runspaceConfiguration)
 {
     return(CreateRunspace(new LocalHost(), runspaceConfiguration));
 }
Beispiel #41
0
 public RunspacePoolInternal(int minRunspaces, int maxRunspaces, System.Management.Automation.Runspaces.RunspaceConfiguration runspaceConfiguration, PSHost host) : this(minRunspaces, maxRunspaces)
 {
     if (runspaceConfiguration == null)
     {
         throw PSTraceSource.NewArgumentNullException("runspaceConfiguration");
     }
     if (host == null)
     {
         throw PSTraceSource.NewArgumentNullException("host");
     }
     this.rsConfig = runspaceConfiguration;
     this.host = host;
     this.pool = new Stack<Runspace>();
     this.runspaceRequestQueue = new Queue<GetRunspaceAsyncResult>();
     this.ultimateRequestQueue = new Queue<GetRunspaceAsyncResult>();
 }
 internal static Collection<PSSnapInTypeAndFormatErrors> GetFormatAndTypesErrors(RunspaceConfiguration runspaceConfiguration, PSHost host, IEnumerable configurationEntryCollection, RunspaceConfigurationCategory category, Collection<string> independentErrors, Collection<int> entryIndicesToRemove)
 {
     Collection<PSSnapInTypeAndFormatErrors> collection = new Collection<PSSnapInTypeAndFormatErrors>();
     string baseFolder = GetBaseFolder(runspaceConfiguration, independentErrors);
     HashSet<string> fullFileNameSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
     int item = -1;
     foreach (object obj2 in configurationEntryCollection)
     {
         string fileName;
         string str3;
         bool flag;
         item++;
         if (category == RunspaceConfigurationCategory.Types)
         {
             TypeConfigurationEntry entry = (TypeConfigurationEntry) obj2;
             fileName = entry.FileName;
             str3 = (entry.PSSnapIn == null) ? runspaceConfiguration.ShellId : entry.PSSnapIn.Name;
             if (fileName != null)
             {
                 goto Label_00DD;
             }
             collection.Add(new PSSnapInTypeAndFormatErrors(str3, entry.TypeData, entry.IsRemove));
             continue;
         }
         FormatConfigurationEntry entry2 = (FormatConfigurationEntry) obj2;
         fileName = entry2.FileName;
         str3 = (entry2.PSSnapIn == null) ? runspaceConfiguration.ShellId : entry2.PSSnapIn.Name;
         if (fileName == null)
         {
             collection.Add(new PSSnapInTypeAndFormatErrors(str3, entry2.FormatData));
             continue;
         }
     Label_00DD:
         flag = false;
         string xmlFileListFileName = GetAndCheckFullFileName(str3, fullFileNameSet, baseFolder, fileName, independentErrors, ref flag);
         if (xmlFileListFileName == null)
         {
             if (flag)
             {
                 entryIndicesToRemove.Add(item);
             }
         }
         else if (xmlFileListFileName.EndsWith("filelist.ps1xml", StringComparison.OrdinalIgnoreCase))
         {
             bool flag2;
             foreach (string str5 in runspaceConfiguration.TypeTable.ReadFiles(str3, xmlFileListFileName, independentErrors, runspaceConfiguration.AuthorizationManager, host, out flag2))
             {
                 string fullPath = GetAndCheckFullFileName(str3, fullFileNameSet, baseFolder, str5, independentErrors, ref flag);
                 if (fullPath != null)
                 {
                     collection.Add(new PSSnapInTypeAndFormatErrors(str3, fullPath));
                 }
             }
         }
         else
         {
             collection.Add(new PSSnapInTypeAndFormatErrors(str3, xmlFileListFileName));
         }
     }
     return collection;
 }
Beispiel #43
0
 public ExecutionContext(PSHost host, RunspaceConfiguration config)
     : this()
 {
     RunspaceConfiguration = config;
     LocalHost = host;
 }
        internal virtual Runspace OpenRunspace()
        {
            HostedSolutionLog.LogStart("OpenRunspace");

            if (runspaceConfiguration == null)
            {
                runspaceConfiguration = RunspaceConfiguration.Create();
            }

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

            ImportGroupPolicyMolude(runSpace);

            HostedSolutionLog.LogEnd("OpenRunspace");
            return runSpace;
        }
Beispiel #45
0
 public static Runspace CreateRunspace(RunspaceConfiguration runspaceConfiguration)
 {
     return CreateRunspace(new LocalHost(), runspaceConfiguration);
 }
Beispiel #46
0
 public static RunspacePool CreateRunspacePool(
     int minRunspaces,
     int maxRunspaces,
     PSHost host)
 {
     using (RunspaceFactory._tracer.TraceMethod())
         return(RunspaceFactory.CreateRunspacePool(minRunspaces, maxRunspaces, RunspaceConfiguration.Create(), host));
 }
Beispiel #47
0
 internal LocalRunspace(PSHost host, RunspaceConfiguration runspaceConfig)
     : base(host, runspaceConfig)
 {
 }
Beispiel #48
0
 internal LocalRunspace(PSHost host, RunspaceConfiguration runspaceConfig)
     : base(host, runspaceConfig)
 {
 }
Beispiel #49
0
 public static RunspacePool CreateRunspacePool(int minRunspaces, int maxRunspaces)
 {
     using (RunspaceFactory._tracer.TraceMethod())
         return(RunspaceFactory.CreateRunspacePool(minRunspaces, maxRunspaces, RunspaceConfiguration.Create(), (PSHost) new DefaultHost(Thread.CurrentThread.CurrentCulture, Thread.CurrentThread.CurrentUICulture)));
 }
Beispiel #50
0
 public static RunspacePool CreateRunspacePool(int minRunspaces, int maxRunspaces, PSHost host)
 {
     return(CreateRunspacePool(minRunspaces, maxRunspaces, RunspaceConfiguration.Create(), host));
 }
Beispiel #51
0
 public static Runspace CreateRunspace(PSHost host)
 {
     using (RunspaceFactory._tracer.TraceMethod())
         return(host != null?RunspaceFactory.CreateRunspace(host, RunspaceConfiguration.Create()) : throw RunspaceFactory._tracer.NewArgumentNullException(nameof(host)));
 }
Beispiel #52
0
 /// <summary>
 /// Creates a RunspacePool using the supplied <paramref name="configuration"/>,
 /// <paramref name="minRunspaces"/> and <paramref name="maxRunspaces"/>
 /// </summary>
 /// <param name="minRunspaces">
 /// The minimum number of Runspaces that can exist in this pool.
 /// Should be greater than or equal to 1.
 /// </param>
 /// <param name="maxRunspaces">
 /// The maximum number of Runspaces that can exist in this pool.
 /// Should be greater than or equal to 1.
 /// </param>
 /// <param name="runspaceConfiguration">
 /// RunspaceConfiguration to use when creating a new Runspace in the
 /// pool.
 /// </param>
 /// <exception cref="ArgumentNullException">
 /// RunspaceConfiguration is null.
 /// </exception>
 /// <param name="host">
 /// The explicit PSHost implementation.
 /// </param>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="runspaceConfiguration"/> is null.
 /// <paramref name="host"/> is null.
 /// </exception>
 /// <exception cref="ArgumentException">
 /// Maximum runspaces is less than 1.
 /// Minimum runspaces is less than 1.
 /// </exception>
 private static RunspacePool CreateRunspacePool(int minRunspaces, int maxRunspaces,
                                                RunspaceConfiguration runspaceConfiguration, PSHost host)
 {
     return(new RunspacePool(minRunspaces,
                             maxRunspaces, runspaceConfiguration, host));
 }
Beispiel #53
0
 public static Runspace CreateRunspace(PSHost host, RunspaceConfiguration runspaceConfiguration)
 {
     return(new LocalRunspace(host, runspaceConfiguration));
 }
Beispiel #54
0
        static Runspace CreateRunspace(PSHost host, RunspaceConfiguration runspaceConfiguration)
        {
            if (host == null)
            {
                throw PSTraceSource.NewArgumentNullException("host");
            }

            if (runspaceConfiguration == null)
            {
                throw PSTraceSource.NewArgumentNullException("runspaceConfiguration");
            }

            return new LocalRunspace(host, runspaceConfiguration);
        }
        /// <summary>
        /// main initialisation routine for the <see cref="Runspace"/>
        /// </summary>
        /// <param name="snapin"><see cref="SnapIn"/> to be initialized together with the <see cref="Runspace"/></param>
        private void InitRunSpace(SnapIn snapin)
        {
            const string MethodName = "InitRunSpace";
            Debug.WriteLine(MethodName + "(" + snapin + ")" + ":entry", ClassName);

            // create a new config from scratch
            PSSnapInException snapOutput = null;
            this.runSpaceConfig = RunspaceConfiguration.Create();

            switch (snapin)
            {
                case SnapIn.Exchange:
                    var serverVersion = GetExchangeServerVersion();
                    switch (serverVersion)
                    {
                        case ExchangeVersion.E2007:
                            // used for force load of the exchange dll's
                            AppDomain.CurrentDomain.AssemblyResolve +=
                                             new ResolveEventHandler(ExchangeUtility.AssemblyResolver2007);

                            this.runSpaceConfig.AddPSSnapIn(Exchange2007SnapIn, out snapOutput);
                            break;
                        case ExchangeVersion.E2010:
                            // used for force load of the exchange dll's
                            AppDomain.CurrentDomain.AssemblyResolve +=
                                             new ResolveEventHandler(ExchangeUtility.AssemblyResolver2010);

                            this.runSpaceConfig.AddPSSnapIn(Exchange2010SnapIn, out snapOutput);
                            break;
                    }
                    break;
            }

            // check snapOutput
            if (snapOutput != null)
            {
                throw snapOutput;
            }

            // create the real Runspace and open it for processing
            this.runSpace = RunspaceFactory.CreateRunspace(this.runSpaceConfig);
            this.runSpace.Open();
            this.runSpaceInvoke = new RunspaceInvoke(this.runSpace);

            Debug.WriteLine(MethodName + ":exit", ClassName);
        }
Beispiel #56
0
 /// <summary>
 /// Creates a RunspacePool using the supplied <paramref name="configuration"/>,
 /// <paramref name="minRunspaces"/> and <paramref name="maxRunspaces"/>
 /// </summary>
 /// <param name="minRunspaces">
 /// The minimum number of Runspaces that can exist in this pool.
 /// Should be greater than or equal to 1.
 /// </param>
 /// <param name="maxRunspaces">
 /// The maximum number of Runspaces that can exist in this pool. 
 /// Should be greater than or equal to 1.
 /// </param>
 /// <param name="runspaceConfiguration">
 /// RunspaceConfiguration to use when creating a new Runspace in the
 /// pool.
 /// </param>        
 /// <exception cref="ArgumentNullException">
 /// RunspaceConfiguration is null.
 /// </exception>
 /// <param name="host">
 /// The explicit PSHost implementation. 
 /// </param>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="runspaceConfiguration"/> is null.
 /// <paramref name="host"/> is null.
 /// </exception>
 /// <exception cref="ArgumentException">
 /// Maximum runspaces is less than 1.
 /// Minimum runspaces is less than 1.
 /// </exception>
 private static RunspacePool CreateRunspacePool(int minRunspaces, int maxRunspaces,
     RunspaceConfiguration runspaceConfiguration, PSHost host)
 {
     return new RunspacePool(minRunspaces,
         maxRunspaces, runspaceConfiguration, host);
 }
 internal void CloseRunspace(Runspace runspace)
 {
     try
     {
         if (runspace != null && runspace.RunspaceStateInfo.State == RunspaceState.Opened)
         {
             runspace.Close();
             runspaceConfiguration = null;
         }
     }
     catch (Exception ex)
     {
         HostedSolutionLog.LogError("Runspace error", ex);
     }
 }
Beispiel #58
0
 internal RunspacePool(int minRunspaces, int maxRunspaces, RunspaceConfiguration runspaceConfiguration, PSHost host)
 {
     throw new NotImplementedException();
 }
Beispiel #59
0
 public static Runspace CreateRunspace(PSHost host, RunspaceConfiguration runspaceConfiguration)
 {
     return new LocalRunspace(host, runspaceConfiguration);
 }
Beispiel #60
0
        // TODO: make sure to implement a Singleton DefaultRunspace pattern
        //internal static LocalRunspace DefaultRunspace { get; private set; }

        public LocalRunspace(PSHost host, RunspaceConfiguration configuration)
            : this(host, configuration, null)
        {

        }