/// <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);
        }
        /// <summary>
        /// Validates the external script info
        /// </summary>
        ///
        /// <param name="host"></param>
        ///
        public void ValidateScriptInfo(Host.PSHost host)
        {
            if (!_signatureChecked)
            {
                ExecutionContext context = Context ?? LocalPipeline.GetExecutionContextFromTLS();

                ReadScriptContents();

                // We have no way to check the signature w/o context because we don't have
                // an AuthorizationManager.  This can happen during initialization when trying
                // to get the CommandMetadata for a script (either to prepopulate the metadata
                // or creating a proxy).  If context can be null under any other circumstances,
                // we need to make sure it's acceptable if the parser is invoked on unsigned scripts.
                if (context != null)
                {
                    CommandDiscovery.ShouldRun(context, host, this, CommandOrigin.Internal);
                    _signatureChecked = true;
                }
            }
        }
Exemple #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, InitialSessionState iss)
        {
#if !UNIX
            // 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

            Context = new ExecutionContext(this, hostInterface, iss);

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

            // Load the iss, resetting everything to it's defaults...
            iss.Bind(Context, /*updateOnly*/ false);

            InitialSessionState.SetSessionStateDrive(Context, true);
        }
Exemple #4
0
        internal string GetDefaultShellSearchPath()
        {
            string shellId          = this.HelpSystem.ExecutionContext.ShellID;
            string pathFromRegistry = CommandDiscovery.GetShellPathFromRegistry(shellId);
            string directoryName;

            if (pathFromRegistry == null)
            {
                directoryName = Path.GetDirectoryName(PsUtils.GetMainModule(Process.GetCurrentProcess()).FileName);
                this.HelpSystem.LastErrors.Add(new ErrorRecord((Exception)HelpProvider.tracer.NewArgumentException("DefaultSearchPath", "HelpErrors", "RegistryPathNotFound", (object)Utils.GetRegistryConfigurationPath(shellId), (object)"\\Path", (object)directoryName), "LoadHelpFileForTargetFailed", ErrorCategory.OpenError, (object)null));
            }
            else
            {
                directoryName = Path.GetDirectoryName(pathFromRegistry);
                if (!Directory.Exists(directoryName))
                {
                    directoryName = Path.GetDirectoryName(PsUtils.GetMainModule(Process.GetCurrentProcess()).FileName);
                    this.HelpSystem.LastErrors.Add(new ErrorRecord((Exception)HelpProvider.tracer.NewArgumentException("DefaultSearchPath", "HelpErrors", "RegistryPathNotFound", (object)Utils.GetRegistryConfigurationPath(shellId), (object)"\\Path", (object)"\\Path", (object)directoryName), "LoadHelpFileForTargetFailed", ErrorCategory.OpenError, (object)null));
                }
            }
            return(directoryName);
        }
Exemple #5
0
        /// <summary>
        /// Each Shell ( minishell ) will have its own path specified by the
        /// registry HKLM\software\microsoft\msh\1\ShellIds\&lt;ShellID&gt;\path. Every help
        /// provider should search this path for content.
        /// </summary>
        /// <returns>string representing base directory of the executing shell.</returns>
        internal string GetDefaultShellSearchPath()
        {
            string shellID     = this.HelpSystem.ExecutionContext.ShellID;
            string returnValue = CommandDiscovery.GetShellPathFromRegistry(shellID);

            if (returnValue == null)
            {
                // use executing assemblies location in case registry entry not found
                returnValue = Path.GetDirectoryName(PsUtils.GetMainModule(System.Diagnostics.Process.GetCurrentProcess()).FileName);
            }
            else
            {
                // Get the directory path of the executing shell
                returnValue = Path.GetDirectoryName(returnValue);
                if (!Directory.Exists(returnValue))
                {
                    // use executing assemblies location in case registry entry not found
                    returnValue = Path.GetDirectoryName(PsUtils.GetMainModule(System.Diagnostics.Process.GetCurrentProcess()).FileName);
                }
            }

            return(returnValue);
        }
Exemple #6
0
        private CommandProcessorBase CreateCommandProcessor(
            out int index,
            ExecutionContext context)
        {
            index = 0;
            CommandProcessorBase commandProcessorBase = (CommandProcessorBase)null;

            if (this._expression != null)
            {
                return((CommandProcessorBase) new ScriptCommandProcessor(ScriptBlock.CreateSynthesized(this._expression, this.NodeToken), context, false));
            }
            bool createScope;
            SessionStateInternal commandSessionState;
            bool   forceSessionState;
            object commandName = this.GetCommandName(out createScope, out index, out commandSessionState, out forceSessionState, context);

            switch (commandName)
            {
            case ScriptBlock scriptblock:
                commandProcessorBase = CommandDiscovery.CreateCommandProcessorForScript(scriptblock, context, createScope);
                if (commandProcessorBase.CommandSessionState == null || forceSessionState)
                {
                    commandProcessorBase.CommandSessionState = commandSessionState;
                    break;
                }
                break;

            case CommandInfo commandInfo:
                commandProcessorBase = context.CommandDiscovery.LookupCommandProcessor(commandInfo, context.EngineSessionState.currentScope.ScopeOrigin, new bool?(false));
                break;

            case string stringParser:
label_7:
                if (string.IsNullOrEmpty(stringParser))
                {
                    throw InterpreterError.NewInterpreterException(commandName, typeof(RuntimeException), (Token)this._elements[0], "BadExpression", (object)((Token)this._elements[0]).TokenText);
                }
                try
                {
                    if (commandSessionState != context.EngineSessionState)
                    {
                        SessionStateInternal engineSessionState = context.EngineSessionState;
                        try
                        {
                            context.EngineSessionState = commandSessionState;
                            commandProcessorBase       = context.CreateCommand(stringParser);
                            break;
                        }
                        finally
                        {
                            context.EngineSessionState = engineSessionState;
                        }
                    }
                    else
                    {
                        commandProcessorBase = context.CreateCommand(stringParser);
                        break;
                    }
                }
                catch (ParseException ex)
                {
                    throw;
                }
                catch (RuntimeException ex)
                {
                    if (ex.ErrorRecord.InvocationInfo == null)
                    {
                        ex.ErrorRecord.SetInvocationInfo(new InvocationInfo((CommandInfo)null, (Token)this._elements[0], context));
                    }
                    throw;
                }

            default:
                stringParser = PSObject.ToStringParser(context, commandName);
                goto label_7;
            }
            if (commandProcessorBase.CommandSessionState == null || forceSessionState)
            {
                commandProcessorBase.CommandSessionState = commandSessionState;
            }
            InternalCommand command = commandProcessorBase.Command;

            command.MyInvocation.ScriptToken = (Token)this._elements[0];
            if (context.IsStrictVersion(2) && this._elements.Count == index + 1 && (this._elements[index - 1] is Token && this._elements[index] is ArrayLiteralNode))
            {
                Token element = (Token)this._elements[index - 1];
                if (element.Script[element.End] == '(')
                {
                    throw InterpreterError.NewInterpreterException((object)null, typeof(RuntimeException), (Token)this._elements[index - 1], "StrictModeFunctionCallWithParens");
                }
            }
            if (createScope)
            {
                switch (command)
                {
                case ScriptCommand _:
                case PSScriptCmdlet _:
                    commandProcessorBase.UseLocalScope = true;
                    commandProcessorBase.CommandScope  = commandProcessorBase.CommandSessionState == null?context.EngineSessionState.NewScope(commandProcessorBase.FromScriptFile) : commandProcessorBase.CommandSessionState.NewScope(commandProcessorBase.FromScriptFile);

                    goto label_27;
                }
            }
            commandProcessorBase.UseLocalScope = false;
            commandProcessorBase.CommandScope  = commandProcessorBase.CommandSessionState.CurrentScope;
label_27:
            commandProcessorBase.Command.CallingToken = (Token)this._elements[0];
            return(commandProcessorBase);
        }
Exemple #7
0
        private static CommandProcessorBase AddCommand(PipelineProcessor pipe, CommandParameterInternal[] commandElements, CommandBaseAst commandBaseAst, CommandRedirection[] redirections, System.Management.Automation.ExecutionContext context)
        {
            object               parameterText;
            IScriptExtent        parameterExtent;
            CommandProcessorBase base2;
            InternalCommand      command;
            string               str3;
            HelpCategory         category;
            CommandAst           ast          = commandBaseAst as CommandAst;
            TokenKind            kind         = (ast != null) ? ast.InvocationOperator : TokenKind.Unknown;
            bool dotSource                    = kind == TokenKind.Dot;
            SessionStateInternal sessionState = null;
            int          index                = 0;
            PSModuleInfo info                 = PSObject.Base(commandElements[0].ArgumentValue) as PSModuleInfo;

            if (info != null)
            {
                if ((info.ModuleType == ModuleType.Binary) && (info.SessionState == null))
                {
                    throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "CantInvokeInBinaryModule", ParserStrings.CantInvokeInBinaryModule, new object[] { info.Name });
                }
                if (info.SessionState == null)
                {
                    throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "CantInvokeInNonImportedModule", ParserStrings.CantInvokeInNonImportedModule, new object[] { info.Name });
                }
                sessionState = info.SessionState.Internal;
                index++;
            }
            CommandParameterInternal internal3 = commandElements[index];

            if (internal3.ParameterNameSpecified)
            {
                parameterText   = internal3.ParameterText;
                parameterExtent = internal3.ParameterExtent;
                if (!internal3.ArgumentSpecified)
                {
                }
            }
            else
            {
                parameterText   = PSObject.Base(internal3.ArgumentValue);
                parameterExtent = internal3.ArgumentExtent;
            }
            string      str         = dotSource ? "." : ((kind == TokenKind.Ampersand) ? "&" : null);
            ScriptBlock scriptblock = parameterText as ScriptBlock;

            if (scriptblock != null)
            {
                base2 = CommandDiscovery.CreateCommandProcessorForScript(scriptblock, context, !dotSource, sessionState);
            }
            else
            {
                CommandInfo commandInfo = parameterText as CommandInfo;
                if (commandInfo != null)
                {
                    base2 = context.CommandDiscovery.LookupCommandProcessor(commandInfo, context.EngineSessionState.CurrentScope.ScopeOrigin, new bool?(!dotSource), sessionState);
                }
                else
                {
                    string str2 = (parameterText as string) ?? PSObject.ToStringParser(context, parameterText);
                    str = str ?? str2;
                    if (string.IsNullOrEmpty(str2))
                    {
                        throw InterpreterError.NewInterpreterException(parameterText, typeof(RuntimeException), parameterExtent, "BadExpression", ParserStrings.BadExpression, new object[] { dotSource ? "." : "&" });
                    }
                    try
                    {
                        if (sessionState != null)
                        {
                            SessionStateInternal engineSessionState = context.EngineSessionState;
                            try
                            {
                                context.EngineSessionState = sessionState;
                                base2 = context.CreateCommand(str2, dotSource);
                                goto Label_025D;
                            }
                            finally
                            {
                                context.EngineSessionState = engineSessionState;
                            }
                        }
                        base2 = context.CreateCommand(str2, dotSource);
                    }

                    catch (RuntimeException exception)
                    {
                        if (exception.ErrorRecord.InvocationInfo == null)
                        {
                            InvocationInfo invocationInfo = new InvocationInfo(null, parameterExtent, context)
                            {
                                InvocationName = str
                            };
                            exception.ErrorRecord.SetInvocationInfo(invocationInfo);
                        }
                        throw;
                    }
                }
            }
Label_025D:
            command             = base2.Command;
            base2.UseLocalScope = !dotSource && ((command is ScriptCommand) || (command is PSScriptCmdlet));
            bool flag2 = base2 is NativeCommandProcessor;

            for (int i = index + 1; i < commandElements.Length; i++)
            {
                CommandParameterInternal parameter = commandElements[i];
                if ((!parameter.ParameterNameSpecified || !parameter.ParameterName.Equals("-", StringComparison.OrdinalIgnoreCase)) || flag2)
                {
                    if (parameter.ArgumentSplatted)
                    {
                        foreach (CommandParameterInternal internal6 in Splat(parameter.ArgumentValue, parameter.ArgumentExtent))
                        {
                            base2.AddParameter(internal6);
                        }
                    }
                    else
                    {
                        base2.AddParameter(parameter);
                    }
                }
            }
            if (base2.IsHelpRequested(out str3, out category))
            {
                base2 = CommandProcessorBase.CreateGetHelpCommandProcessor(context, str3, category);
            }
            base2.Command.InvocationExtent            = commandBaseAst.Extent;
            base2.Command.MyInvocation.ScriptPosition = commandBaseAst.Extent;
            base2.Command.MyInvocation.InvocationName = str;
            pipe.Add(base2);
            bool flag3 = false;
            bool flag4 = false;
            bool flag5 = false;
            bool flag6 = false;

            if (redirections != null)
            {
                foreach (CommandRedirection redirection in redirections)
                {
                    redirection.Bind(pipe, base2, context);
                    switch (redirection.FromStream)
                    {
                    case RedirectionStream.All:
                        flag3 = true;
                        flag4 = true;
                        flag5 = true;
                        flag6 = true;
                        break;

                    case RedirectionStream.Error:
                        flag3 = true;
                        break;

                    case RedirectionStream.Warning:
                        flag4 = true;
                        break;

                    case RedirectionStream.Verbose:
                        flag5 = true;
                        break;

                    case RedirectionStream.Debug:
                        flag6 = true;
                        break;
                    }
                }
            }
            if (!flag3)
            {
                if (context.ShellFunctionErrorOutputPipe != null)
                {
                    base2.CommandRuntime.ErrorOutputPipe = context.ShellFunctionErrorOutputPipe;
                }
                else
                {
                    base2.CommandRuntime.ErrorOutputPipe.ExternalWriter = context.ExternalErrorOutput;
                }
            }
            if (!flag4 && (context.ExpressionWarningOutputPipe != null))
            {
                base2.CommandRuntime.WarningOutputPipe = context.ExpressionWarningOutputPipe;
                flag4 = true;
            }
            if (!flag5 && (context.ExpressionVerboseOutputPipe != null))
            {
                base2.CommandRuntime.VerboseOutputPipe = context.ExpressionVerboseOutputPipe;
                flag5 = true;
            }
            if (!flag6 && (context.ExpressionDebugOutputPipe != null))
            {
                base2.CommandRuntime.DebugOutputPipe = context.ExpressionDebugOutputPipe;
                flag6 = true;
            }
            if ((context.CurrentCommandProcessor != null) && (context.CurrentCommandProcessor.CommandRuntime != null))
            {
                if (!flag4 && (context.CurrentCommandProcessor.CommandRuntime.WarningOutputPipe != null))
                {
                    base2.CommandRuntime.WarningOutputPipe = context.CurrentCommandProcessor.CommandRuntime.WarningOutputPipe;
                }
                if (!flag5 && (context.CurrentCommandProcessor.CommandRuntime.VerboseOutputPipe != null))
                {
                    base2.CommandRuntime.VerboseOutputPipe = context.CurrentCommandProcessor.CommandRuntime.VerboseOutputPipe;
                }
                if (!flag6 && (context.CurrentCommandProcessor.CommandRuntime.DebugOutputPipe != null))
                {
                    base2.CommandRuntime.DebugOutputPipe = context.CurrentCommandProcessor.CommandRuntime.DebugOutputPipe;
                }
            }
            return(base2);
        }
Exemple #8
0
        private void HandleRunspaceCreated(object sender, RunspaceCreatedEventArgs args)
        {
            bool flag = false;

            if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
            {
                args.Runspace.ExecutionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage;
                flag = true;
            }
            try
            {
                string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                args.Runspace.ExecutionContext.EngineSessionState.SetLocation(folderPath);
            }
            catch (ArgumentException)
            {
            }
            catch (ProviderNotFoundException)
            {
            }
            catch (DriveNotFoundException)
            {
            }
            catch (ProviderInvocationException)
            {
            }
            if (this.configHash != null)
            {
                if (this.configHash.ContainsKey(ConfigFileContants.EnvironmentVariables))
                {
                    Hashtable hashtable = this.configHash[ConfigFileContants.EnvironmentVariables] as Hashtable;
                    if (hashtable != null)
                    {
                        foreach (DictionaryEntry entry in hashtable)
                        {
                            string introduced76 = entry.Key.ToString();
                            this.InvokeScript(new Command(StringUtil.Format("$env:{0} = \"{1}\"", introduced76, entry.Value.ToString()), true, false), args);
                        }
                    }
                }
                if (this.configHash.ContainsKey(ConfigFileContants.VariableDefinitions))
                {
                    Hashtable[] hashtableArray = DISCPowerShellConfiguration.TryGetHashtableArray(this.configHash[ConfigFileContants.VariableDefinitions]);
                    if (hashtableArray != null)
                    {
                        foreach (Hashtable hashtable2 in hashtableArray)
                        {
                            if (hashtable2.ContainsKey(ConfigFileContants.VariableValueToken))
                            {
                                string      str2  = DISCPowerShellConfiguration.TryGetValue(hashtable2, ConfigFileContants.VariableNameToken);
                                ScriptBlock block = hashtable2[ConfigFileContants.VariableValueToken] as ScriptBlock;
                                if (!string.IsNullOrEmpty(str2) && (block != null))
                                {
                                    block.SessionStateInternal = args.Runspace.ExecutionContext.EngineSessionState;
                                    PowerShell powershell = PowerShell.Create();
                                    powershell.AddCommand(new Command("Invoke-Command")).AddParameter("ScriptBlock", block).AddParameter("NoNewScope");
                                    powershell.AddCommand(new Command("Set-Variable")).AddParameter("Name", str2);
                                    this.InvokePowerShell(powershell, args);
                                }
                            }
                        }
                    }
                }
                if (this.configHash.ContainsKey(ConfigFileContants.ScriptsToProcess))
                {
                    string[] strArray = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.ScriptsToProcess]);
                    if (strArray != null)
                    {
                        foreach (string str3 in strArray)
                        {
                            if (!string.IsNullOrEmpty(str3))
                            {
                                this.InvokeScript(new Command(str3, true, false), args);
                            }
                        }
                    }
                }
                bool flag2 = false;
                if (this.configHash.ContainsKey(ConfigFileContants.VisibleAliases))
                {
                    string[] strArray2 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleAliases]);
                    if (strArray2 != null)
                    {
                        flag2 = true;
                        foreach (KeyValuePair <string, AliasInfo> pair in args.Runspace.ExecutionContext.EngineSessionState.GetAliasTable())
                        {
                            bool flag3 = false;
                            foreach (string str4 in strArray2)
                            {
                                if (!string.IsNullOrEmpty(str4))
                                {
                                    IEnumerable <WildcardPattern> patternList = this.CreateKeyPatternList(str4);
                                    if (this.MatchKeyPattern(patternList, pair.Key))
                                    {
                                        pair.Value.Visibility = SessionStateEntryVisibility.Public;
                                        flag3 = true;
                                    }
                                }
                            }
                            if (!flag3)
                            {
                                pair.Value.Visibility = SessionStateEntryVisibility.Private;
                            }
                        }
                    }
                }
                if (this.configHash.ContainsKey(ConfigFileContants.VisibleCmdlets))
                {
                    string[] strArray3 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleCmdlets]);
                    if (strArray3 != null)
                    {
                        flag2 = true;
                        foreach (KeyValuePair <string, List <CmdletInfo> > pair2 in args.Runspace.ExecutionContext.EngineSessionState.GetCmdletTable())
                        {
                            bool flag4 = false;
                            foreach (string str5 in strArray3)
                            {
                                if (!string.IsNullOrEmpty(str5))
                                {
                                    IEnumerable <WildcardPattern> enumerable2 = this.CreateKeyPatternList(str5);
                                    if (this.MatchKeyPattern(enumerable2, pair2.Key))
                                    {
                                        foreach (CmdletInfo info in pair2.Value)
                                        {
                                            info.Visibility = SessionStateEntryVisibility.Public;
                                            flag4           = true;
                                        }
                                    }
                                }
                            }
                            if (!flag4)
                            {
                                foreach (CmdletInfo info2 in pair2.Value)
                                {
                                    info2.Visibility = SessionStateEntryVisibility.Private;
                                }
                            }
                        }
                    }
                }
                List <string> list  = new List <string>();
                bool          flag5 = false;
                if (this.configHash.ContainsKey(ConfigFileContants.VisibleFunctions))
                {
                    string[] strArray4 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleFunctions]);
                    if (strArray4 != null)
                    {
                        flag2 = true;
                        flag5 = true;
                        list.AddRange(strArray4);
                    }
                }
                if (!flag5 && this.configHash.ContainsKey(ConfigFileContants.FunctionDefinitions))
                {
                    Hashtable[] hashtableArray2 = DISCPowerShellConfiguration.TryGetHashtableArray(this.configHash[ConfigFileContants.FunctionDefinitions]);
                    if (hashtableArray2 != null)
                    {
                        foreach (Hashtable hashtable3 in hashtableArray2)
                        {
                            string str6 = DISCPowerShellConfiguration.TryGetValue(hashtable3, ConfigFileContants.FunctionNameToken);
                            if (!string.IsNullOrEmpty(str6))
                            {
                                list.Add(str6);
                            }
                        }
                    }
                }
                string str7 = DISCPowerShellConfiguration.TryGetValue(this.configHash, ConfigFileContants.SessionType);
                if (!string.IsNullOrEmpty(str7))
                {
                    SessionType type = (SessionType)Enum.Parse(typeof(SessionType), str7, true);
                    if (type == SessionType.RestrictedRemoteServer)
                    {
                        list.Add("Get-Command");
                        list.Add("Get-FormatData");
                        list.Add("Select-Object");
                        list.Add("Get-Help");
                        list.Add("Measure-Object");
                        list.Add("Out-Default");
                        list.Add("Exit-PSSession");
                    }
                }
                if (list.Count > 0)
                {
                    foreach (DictionaryEntry entry2 in args.Runspace.ExecutionContext.EngineSessionState.GetFunctionTable())
                    {
                        bool         flag6 = false;
                        string       key   = entry2.Key.ToString();
                        FunctionInfo info3 = entry2.Value as FunctionInfo;
                        if (info3 != null)
                        {
                            foreach (string str9 in list)
                            {
                                if (!string.IsNullOrEmpty(str9))
                                {
                                    IEnumerable <WildcardPattern> enumerable3 = this.CreateKeyPatternList(str9);
                                    if (this.MatchKeyPattern(enumerable3, key))
                                    {
                                        info3.Visibility = SessionStateEntryVisibility.Public;
                                        flag6            = true;
                                    }
                                }
                            }
                            if (!flag6 && flag5)
                            {
                                info3.Visibility = SessionStateEntryVisibility.Private;
                            }
                        }
                    }
                }
                if (this.configHash.ContainsKey(ConfigFileContants.VisibleProviders))
                {
                    string[] strArray5 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleProviders]);
                    if (strArray5 != null)
                    {
                        flag2 = true;
                        IDictionary <string, List <ProviderInfo> > providers = args.Runspace.ExecutionContext.EngineSessionState.Providers;
                        Collection <string> collection = new Collection <string>();
                        foreach (KeyValuePair <string, List <ProviderInfo> > pair3 in providers)
                        {
                            bool flag7 = false;
                            foreach (string str10 in strArray5)
                            {
                                if (!string.IsNullOrEmpty(str10))
                                {
                                    IEnumerable <WildcardPattern> enumerable4 = this.CreateKeyPatternList(str10);
                                    if (this.MatchKeyPattern(enumerable4, pair3.Key))
                                    {
                                        flag7 = true;
                                    }
                                }
                            }
                            if (!flag7)
                            {
                                collection.Add(pair3.Key);
                            }
                        }
                        foreach (string str11 in collection)
                        {
                            args.Runspace.ExecutionContext.EngineSessionState.Providers.Remove(str11);
                        }
                    }
                }
                if (flag2)
                {
                    CmdletInfo cmdlet = args.Runspace.ExecutionContext.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Import-Module");
                    IDictionary <string, AliasInfo> aliasTable = args.Runspace.ExecutionContext.EngineSessionState.GetAliasTable();
                    PSModuleAutoLoadingPreference   preference = CommandDiscovery.GetCommandDiscoveryPreference(args.Runspace.ExecutionContext, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference");
                    bool flag8 = (cmdlet != null) && (cmdlet.Visibility != SessionStateEntryVisibility.Private);
                    bool flag9 = ((aliasTable != null) && aliasTable.ContainsKey("ipmo")) && (aliasTable["ipmo"].Visibility != SessionStateEntryVisibility.Private);
                    if ((flag8 || flag9) && (preference == PSModuleAutoLoadingPreference.None))
                    {
                        throw new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.DISCVisibilityAndAutoLoadingCannotBeBothSpecified, new object[] { "Import-Module", "ipmo", ConfigFileContants.VisibleCmdlets, ConfigFileContants.VisibleAliases, ConfigFileContants.VisibleFunctions, ConfigFileContants.VisibleProviders }));
                    }
                }
                if (this.configHash.ContainsKey(ConfigFileContants.LanguageMode))
                {
                    PSLanguageMode mode = (PSLanguageMode)Enum.Parse(typeof(PSLanguageMode), this.configHash[ConfigFileContants.LanguageMode].ToString(), true);
                    if (flag && (mode != PSLanguageMode.ConstrainedLanguage))
                    {
                        throw new PSInvalidOperationException(RemotingErrorIdStrings.CannotCreateRunspaceInconsistentState);
                    }
                    args.Runspace.ExecutionContext.LanguageMode = mode;
                }
                if (this.configHash.ContainsKey(ConfigFileContants.ExecutionPolicy))
                {
                    ExecutionPolicy policy  = (ExecutionPolicy)Enum.Parse(typeof(ExecutionPolicy), this.configHash[ConfigFileContants.ExecutionPolicy].ToString(), true);
                    string          shellID = args.Runspace.ExecutionContext.ShellID;
                    SecuritySupport.SetExecutionPolicy(ExecutionPolicyScope.Process, policy, shellID);
                }
            }
            Command cmdToRun = null;

            if (!string.IsNullOrEmpty(this.configData.StartupScript))
            {
                cmdToRun = new Command(this.configData.StartupScript, false, false);
            }
            else if (!string.IsNullOrEmpty(this.configData.InitializationScriptForOutOfProcessRunspace))
            {
                cmdToRun = new Command(this.configData.InitializationScriptForOutOfProcessRunspace, true, false);
            }
            if (cmdToRun != null)
            {
                this.InvokeScript(cmdToRun, args);
                if (this.localRunspacePool.RunspacePoolStateInfo.State == RunspacePoolState.Opening)
                {
                    object valueToConvert = args.Runspace.SessionStateProxy.PSVariable.GetValue("global:PSApplicationPrivateData");
                    if (valueToConvert != null)
                    {
                        this.applicationPrivateData = (PSPrimitiveDictionary)LanguagePrimitives.ConvertTo(valueToConvert, typeof(PSPrimitiveDictionary), true, CultureInfo.InvariantCulture, null);
                    }
                }
            }
        }
 internal AutomationEngine(
     PSHost hostInterface,
     RunspaceConfiguration runspaceConfiguration,
     InitialSessionState iss)
 {
     this._context         = runspaceConfiguration == null ? new ExecutionContext(this, hostInterface, iss) : new ExecutionContext(this, hostInterface, runspaceConfiguration);
     this.EngineParser     = new Parser();
     this.commandDiscovery = new CommandDiscovery(this._context);
     if (runspaceConfiguration != null)
     {
         runspaceConfiguration.Bind(this._context);
     }
     else
     {
         iss.Bind(this._context, false);
     }
     try
     {
         bool flag1 = true;
         if (this._context.EngineSessionState.ProviderCount > 0)
         {
             if (this._context.EngineSessionState.CurrentDrive == (PSDriveInfo)null)
             {
                 bool flag2 = false;
                 try
                 {
                     Collection <PSDriveInfo> drives = this._context.EngineSessionState.GetSingleProvider(this._context.ProviderNames.FileSystem).Drives;
                     if (drives != null)
                     {
                         if (drives.Count > 0)
                         {
                             this._context.EngineSessionState.CurrentDrive = drives[0];
                             flag2 = true;
                         }
                     }
                 }
                 catch (ProviderNotFoundException ex)
                 {
                 }
                 if (!flag2)
                 {
                     Collection <PSDriveInfo> collection = this._context.EngineSessionState.Drives((string)null);
                     if (collection != null && collection.Count > 0)
                     {
                         this._context.EngineSessionState.CurrentDrive = collection[0];
                     }
                     else
                     {
                         this._context.ReportEngineStartupError((Exception) new ItemNotFoundException(Environment.CurrentDirectory, "PathNotFound"));
                         flag1 = false;
                     }
                 }
             }
             if (flag1)
             {
                 this._context.EngineSessionState.SetLocation(Environment.CurrentDirectory, new CmdletProviderContext(this._context));
             }
         }
         this._context.EngineSessionState.SetVariableAtScope((PSVariable) new QuestionMarkVariable(this._context), "global", true, CommandOrigin.Internal);
     }
     catch (Exception ex)
     {
         CommandProcessorBase.CheckForSevereException(ex);
     }
 }
Exemple #10
0
 internal AliasHelpProvider(HelpSystem helpSystem) : base(helpSystem)
 {
     this._sessionState = helpSystem.ExecutionContext.SessionState;
     this._commandDiscovery = helpSystem.ExecutionContext.CommandDiscovery;
     this._context = helpSystem.ExecutionContext;
 }
Exemple #11
0
 internal void AddCmdletInfoToCache(CmdletInfo newCmdletInfo) => CommandDiscovery.AddCmdletInfoToCache(this._context.EngineSessionState, newCmdletInfo);
Exemple #12
0
 private CmdletInfo NewCmdletInfo(SessionStateCmdletEntry entry) => CommandDiscovery.NewCmdletInfo(entry, this._context);
Exemple #13
0
        internal CommandProcessorBase LookupCommandProcessor(
            CommandInfo commandInfo,
            CommandOrigin commandOrigin,
            bool?useLocalScope)
        {
            if (commandInfo.CommandType == CommandTypes.Alias && (commandOrigin == CommandOrigin.Internal || commandInfo.Visibility == SessionStateEntryVisibility.Public))
            {
                AliasInfo aliasInfo = (AliasInfo)commandInfo;
                commandInfo = aliasInfo.ResolvedCommand;
                if (commandInfo == null)
                {
                    CommandNotFoundException notFoundException = new CommandNotFoundException(aliasInfo.Name, (Exception)null, "AliasNotResolvedException", new object[1]
                    {
                        (object)aliasInfo.UnresolvedCommandName
                    });
                    CommandDiscovery.tracer.TraceException((Exception)notFoundException);
                    throw notFoundException;
                }
                PSSQMAPI.IncrementData(CommandTypes.Alias);
            }
            CommandDiscovery.ShouldRun(this._context, (PSHost)this._context.EngineHostInterface, commandInfo, commandOrigin);
            CommandProcessorBase commandProcessorBase;

            switch (commandInfo.CommandType)
            {
            case CommandTypes.Function:
            case CommandTypes.Filter:
                FunctionInfo     functionInfo = (FunctionInfo)commandInfo;
                ExecutionContext context1     = this._context;
                bool?            nullable1    = useLocalScope;
                int num1 = nullable1.HasValue ? (nullable1.GetValueOrDefault() ? 1 : 0) : 1;
                commandProcessorBase = CommandDiscovery.CreateCommandProcessorForScript(functionInfo, context1, num1 != 0);
                break;

            case CommandTypes.Cmdlet:
                commandProcessorBase = (CommandProcessorBase) new CommandProcessor((CmdletInfo)commandInfo, this._context);
                break;

            case CommandTypes.ExternalScript:
                ExternalScriptInfo externalScriptInfo = (ExternalScriptInfo)commandInfo;
                externalScriptInfo.SignatureChecked = true;
                try
                {
                    if (!this._context.IsSingleShell)
                    {
                        ExternalScriptInfo scriptInfo = externalScriptInfo;
                        bool?nullable2 = useLocalScope;
                        int  num2      = nullable2.HasValue ? (nullable2.GetValueOrDefault() ? 1 : 0) : 1;
                        commandProcessorBase = this.CreateScriptProcessorForMiniShell(scriptInfo, num2 != 0);
                        break;
                    }
                    ExternalScriptInfo           scriptInfo1           = externalScriptInfo;
                    RunspaceConfigForSingleShell runspaceConfiguration = this._context.RunspaceConfiguration as RunspaceConfigForSingleShell;
                    bool?nullable3 = useLocalScope;
                    int  num3      = nullable3.HasValue ? (nullable3.GetValueOrDefault() ? 1 : 0) : 1;
                    commandProcessorBase = this.CreateScriptProcessorForSingleShell(scriptInfo1, runspaceConfiguration, num3 != 0);
                    break;
                }
                catch (ScriptRequiresSyntaxException ex)
                {
                    CommandNotFoundException notFoundException = new CommandNotFoundException(ex.Message, (Exception)ex);
                    CommandDiscovery.tracer.TraceException((Exception)notFoundException);
                    throw notFoundException;
                }
                catch (PSArgumentException ex)
                {
                    CommandNotFoundException notFoundException = new CommandNotFoundException(commandInfo.Name, (Exception)ex, "ScriptRequiresInvalidFormat", new object[0]);
                    CommandDiscovery.tracer.TraceException((Exception)notFoundException);
                    throw notFoundException;
                }

            case CommandTypes.Application:
                commandProcessorBase = (CommandProcessorBase) new NativeCommandProcessor((ApplicationInfo)commandInfo, this._context);
                break;

            case CommandTypes.Script:
                ScriptInfo       scriptInfo2 = (ScriptInfo)commandInfo;
                ExecutionContext context2    = this._context;
                bool?            nullable4   = useLocalScope;
                int num4 = nullable4.HasValue ? (nullable4.GetValueOrDefault() ? 1 : 0) : 1;
                commandProcessorBase = CommandDiscovery.CreateCommandProcessorForScript(scriptInfo2, context2, num4 != 0);
                break;

            default:
                CommandNotFoundException notFoundException1 = new CommandNotFoundException(commandInfo.Name, (Exception)null, "CommandNotFoundException", new object[0]);
                CommandDiscovery.tracer.TraceException((Exception)notFoundException1);
                throw notFoundException1;
            }
            PSSQMAPI.IncrementData(commandInfo.CommandType);
            commandProcessorBase.Command.CommandOriginInternal       = commandOrigin;
            commandProcessorBase.Command.MyInvocation.InvocationName = commandInfo.Name;
            return(commandProcessorBase);
        }
 internal GeneralHelpProvider(HelpSystem helpSystem)
     : base(helpSystem)
 {
     using (GeneralHelpProvider.tracer.TraceConstructor((object)this))
         this._commandDiscovery = helpSystem.ExecutionContext.CommandDiscovery;
 }
Exemple #15
0
 internal AliasHelpProvider(HelpSystem helpSystem) : base(helpSystem)
 {
     this._sessionState     = helpSystem.ExecutionContext.SessionState;
     this._commandDiscovery = helpSystem.ExecutionContext.CommandDiscovery;
     this._context          = helpSystem.ExecutionContext;
 }