Exemple #1
0
        public static void ImportJsonDotNetModule(Cmdlet cmdlet)
        {
            const string jsonDotNetAssemblyName = "Newtonsoft.Json, Version=7.0.0.0";

            // Check if the Newtonsoft.Json.dll assembly is loaded.
            try
            {
                System.Reflection.Assembly.Load(new AssemblyName(jsonDotNetAssemblyName));
            }
            catch (System.IO.FileNotFoundException)
            {
                // It is not, try to load it.
                // Make sure that PSModuleAutoLoadingPreference is not set to 'None'.
                PSModuleAutoLoadingPreference moduleAutoLoadingPreference =
                    CommandDiscovery.GetCommandDiscoveryPreference(cmdlet.Context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference");
                if (moduleAutoLoadingPreference == PSModuleAutoLoadingPreference.None)
                {
                    cmdlet.ThrowTerminatingError(new ErrorRecord(
                                                     new NotSupportedException(WebCmdletStrings.PSModuleAutoloadingPreferenceNotEnable),
                                                     "PSModuleAutoloadingPreferenceNotEnable",
                                                     ErrorCategory.NotEnabled,
                                                     null));
                }

                // Use module auto-loading to import Json.Net.
                var        jsonNetModulePath = Path.Combine(System.Environment.GetEnvironmentVariable("ProgramFiles"), @"WindowsPowerShell\Modules\Json.Net");
                CmdletInfo cmdletInfo        = cmdlet.Context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Import-Module");
                Exception  exception;
                Collection <PSModuleInfo> importedModule = CommandDiscovery.AutoloadSpecifiedModule(jsonNetModulePath, cmdlet.Context, cmdletInfo.Visibility, out exception);

                if ((importedModule == null) || (importedModule.Count == 0))
                {
                    string errorMessage = StringUtil.Format(WebCmdletStrings.JsonNetModuleRequired, WebCmdletStrings.CouldNotAutoImportJsonNetModule);

                    cmdlet.ThrowTerminatingError(new ErrorRecord(
                                                     new NotSupportedException(errorMessage, exception),
                                                     "CouldNotAutoImportJsonNetModule",
                                                     ErrorCategory.InvalidOperation,
                                                     null));
                }

                // Finally, ensure that the Newtonsoft.Json.dll assembly was loaded.
                try
                {
                    System.Reflection.Assembly.Load(new AssemblyName(jsonDotNetAssemblyName));
                }
                catch (System.IO.FileNotFoundException)
                {
                    string errorMessage = StringUtil.Format(
                        WebCmdletStrings.JsonNetModuleRequired,
                        StringUtil.Format(WebCmdletStrings.JsonNetModuleFilesRequired, jsonNetModulePath));

                    cmdlet.ThrowTerminatingError(new ErrorRecord(
                                                     new NotSupportedException(errorMessage),
                                                     "JsonNetModuleRequired",
                                                     ErrorCategory.NotInstalled,
                                                     null));
                }
            }
        }
Exemple #2
0
        /// <summary>
        /// Gets a list of matching commands.
        /// </summary>
        /// <param name="pattern">Command pattern.</param>
        /// <param name="context">Execution context.</param>
        /// <param name="commandOrigin">Command origin.</param>
        /// <param name="rediscoverImportedModules">If true, rediscovers imported modules.</param>
        /// <param name="moduleVersionRequired">Specific module version to be required.</param>
        /// <param name="useFuzzyMatching">Use fuzzy matching.</param>
        /// <param name="useAbbreviationExpansion">Use abbreviation expansion for matching.</param>
        /// <returns>Returns matching CommandInfo IEnumerable.</returns>
        internal static IEnumerable <CommandInfo> GetMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false, bool moduleVersionRequired = false, bool useFuzzyMatching = false, bool useAbbreviationExpansion = false)
        {
            // Otherwise, if it had wildcards, just return the "AvailableCommand"
            // type of command info.
            WildcardPattern commandPattern = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);

            CmdletInfo cmdletInfo = context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Get-Module");
            PSModuleAutoLoadingPreference moduleAutoLoadingPreference = CommandDiscovery.GetCommandDiscoveryPreference(context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference");

            if ((moduleAutoLoadingPreference != PSModuleAutoLoadingPreference.None) &&
                ((commandOrigin == CommandOrigin.Internal) || ((cmdletInfo != null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public))))
            {
                foreach (string modulePath in GetDefaultAvailableModuleFiles(isForAutoDiscovery: false, context))
                {
                    // Skip modules that have already been loaded so that we don't expose private commands.
                    string moduleName                  = Path.GetFileNameWithoutExtension(modulePath);
                    List <PSModuleInfo> modules        = context.Modules.GetExactMatchModules(moduleName, all: false, exactMatch: true);
                    PSModuleInfo        tempModuleInfo = null;

                    if (modules.Count != 0)
                    {
                        // 1. We continue to the next module path if we don't want to re-discover those imported modules
                        // 2. If we want to re-discover the imported modules, but one or more commands from the module were made private,
                        //    then we don't do re-discovery
                        if (!rediscoverImportedModules || modules.Exists(module => module.ModuleHasPrivateMembers))
                        {
                            continue;
                        }

                        if (modules.Count == 1)
                        {
                            PSModuleInfo psModule = modules[0];
                            tempModuleInfo = new PSModuleInfo(psModule.Name, psModule.Path, context: null, sessionState: null);
                            tempModuleInfo.SetModuleBase(psModule.ModuleBase);

                            foreach (KeyValuePair <string, CommandInfo> entry in psModule.ExportedCommands)
                            {
                                if (commandPattern.IsMatch(entry.Value.Name) ||
                                    (useFuzzyMatching && FuzzyMatcher.IsFuzzyMatch(entry.Value.Name, pattern)) ||
                                    (useAbbreviationExpansion && string.Equals(pattern, AbbreviateName(entry.Value.Name), StringComparison.OrdinalIgnoreCase)))
                                {
                                    CommandInfo current = null;
                                    switch (entry.Value.CommandType)
                                    {
                                    case CommandTypes.Alias:
                                        current = new AliasInfo(entry.Value.Name, definition: null, context);
                                        break;

                                    case CommandTypes.Function:
                                        current = new FunctionInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                        break;

                                    case CommandTypes.Filter:
                                        current = new FilterInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                        break;

                                    case CommandTypes.Configuration:
                                        current = new ConfigurationInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context);
                                        break;

                                    case CommandTypes.Cmdlet:
                                        current = new CmdletInfo(entry.Value.Name, implementingType: null, helpFile: null, PSSnapin: null, context);
                                        break;

                                    default:
                                        Dbg.Assert(false, "cannot be hit");
                                        break;
                                    }

                                    current.Module = tempModuleInfo;
                                    yield return(current);
                                }
                            }

                            continue;
                        }
                    }

                    string moduleShortName = Path.GetFileNameWithoutExtension(modulePath);

                    IDictionary <string, CommandTypes> exportedCommands = AnalysisCache.GetExportedCommands(modulePath, testOnly: false, context);

                    if (exportedCommands == null)
                    {
                        continue;
                    }

                    tempModuleInfo = new PSModuleInfo(moduleShortName, modulePath, sessionState: null, context: null);
                    if (InitialSessionState.IsEngineModule(moduleShortName))
                    {
                        tempModuleInfo.SetModuleBase(Utils.DefaultPowerShellAppBase);
                    }

                    // moduleVersionRequired is bypassed by FullyQualifiedModule from calling method. This is the only place where guid will be involved.
                    if (moduleVersionRequired && modulePath.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
                    {
                        tempModuleInfo.SetVersion(ModuleIntrinsics.GetManifestModuleVersion(modulePath));
                        tempModuleInfo.SetGuid(ModuleIntrinsics.GetManifestGuid(modulePath));
                    }

                    foreach (KeyValuePair <string, CommandTypes> pair in exportedCommands)
                    {
                        string       commandName  = pair.Key;
                        CommandTypes commandTypes = pair.Value;

                        if (commandPattern.IsMatch(commandName) ||
                            (useFuzzyMatching && FuzzyMatcher.IsFuzzyMatch(commandName, pattern)) ||
                            (useAbbreviationExpansion && string.Equals(pattern, AbbreviateName(commandName), StringComparison.OrdinalIgnoreCase)))
                        {
                            bool shouldExportCommand = true;

                            // Verify that we don't already have it represented in the initial session state.
                            if ((context.InitialSessionState != null) && (commandOrigin == CommandOrigin.Runspace))
                            {
                                foreach (SessionStateCommandEntry commandEntry in context.InitialSessionState.Commands[commandName])
                                {
                                    string moduleCompareName = null;

                                    if (commandEntry.Module != null)
                                    {
                                        moduleCompareName = commandEntry.Module.Name;
                                    }
                                    else if (commandEntry.PSSnapIn != null)
                                    {
                                        moduleCompareName = commandEntry.PSSnapIn.Name;
                                    }

                                    if (string.Equals(moduleShortName, moduleCompareName, StringComparison.OrdinalIgnoreCase))
                                    {
                                        if (commandEntry.Visibility == SessionStateEntryVisibility.Private)
                                        {
                                            shouldExportCommand = false;
                                        }
                                    }
                                }
                            }

                            if (shouldExportCommand)
                            {
                                if ((commandTypes & CommandTypes.Alias) == CommandTypes.Alias)
                                {
                                    yield return(new AliasInfo(commandName, null, context)
                                    {
                                        Module = tempModuleInfo
                                    });
                                }

                                if ((commandTypes & CommandTypes.Cmdlet) == CommandTypes.Cmdlet)
                                {
                                    yield return(new CmdletInfo(commandName, implementingType: null, helpFile: null, PSSnapin: null, context: context)
                                    {
                                        Module = tempModuleInfo
                                    });
                                }

                                if ((commandTypes & CommandTypes.Function) == CommandTypes.Function)
                                {
                                    yield return(new FunctionInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
                                    {
                                        Module = tempModuleInfo
                                    });
                                }

                                if ((commandTypes & CommandTypes.Configuration) == CommandTypes.Configuration)
                                {
                                    yield return(new ConfigurationInfo(commandName, ScriptBlock.EmptyScriptBlock, context)
                                    {
                                        Module = tempModuleInfo
                                    });
                                }
                            }
                        }
                    }
                }
            }
        }
Exemple #3
0
            public bool MoveNext()
            {
                try
                {
                    int num = this.__1__state;
                    if (num != 0)
                    {
                        if (num == 3)
                        {
                            this.__1__state = 2;
                            this.__m__Finally1e();
                        }
                        if (num == 7)
                        {
                            this.__1__state = 5;
                            this.__m__Finally22();
                        }
                    }
                    else
                    {
                        this.__1__state           = -1;
                        this._commandPattern_5__b = new WildcardPattern(this.pattern, WildcardOptions.IgnoreCase);
                        this._cmdletInfo_5__c     = this.context.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Get-Module");
                        aa__ = CommandDiscovery.GetCommandDiscoveryPreference(this.context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference");
                        if ((aa__ != PSModuleAutoLoadingPreference.None) && ((this.commandOrigin == CommandOrigin.Internal) || ((this._cmdletInfo_5__c != null) && (this._cmdletInfo_5__c.Visibility == SessionStateEntryVisibility.Public))))
                        {
                            this.__7__wrap1b = ModuleUtils.GetDefaultAvailableModuleFiles(true, false, this.context).GetEnumerator();
                            this.__1__state  = 1;
                            while (this.__7__wrap1b.MoveNext())
                            {
                                this._modulePath_5__e      = this.__7__wrap1b.Current;
                                this._moduleName_5__f      = Path.GetFileNameWithoutExtension(this._modulePath_5__e);
                                this._modules_5__10        = this.context.Modules.GetExactMatchModules(this._moduleName_5__f, false, true);
                                this._tempModuleInfo_5__11 = null;
                                if (this._modules_5__10.Count != 0)
                                {
                                    if (!this.rediscoverImportedModules)
                                    {
                                        continue;
                                    }
                                    if (this._modules_5__10.Exists(new Predicate <PSModuleInfo>(ModuleUtils.GetMatchingCommands_b__8)))
                                    {
                                        continue;
                                    }
                                    if (this._modules_5__10.Count == 1)
                                    {
                                        this._psModule_5__12       = this._modules_5__10[0];
                                        this._tempModuleInfo_5__11 = new PSModuleInfo(this._psModule_5__12.Name, this._psModule_5__12.Path, null, null);
                                        this._tempModuleInfo_5__11.SetModuleBase(this._psModule_5__12.ModuleBase);
                                        this.__7__wrap1d = this._psModule_5__12.ExportedCommands.GetEnumerator();
                                        this.__1__state  = 2;
                                        while (this.__7__wrap1d.MoveNext())
                                        {
                                            this._entry_5__13 = this.__7__wrap1d.Current;
                                            if (!this._commandPattern_5__b.IsMatch(this._entry_5__13.Value.Name))
                                            {
                                                continue;
                                            }
                                            this._current_5__14 = null;
                                            switch (this._entry_5__13.Value.CommandType)
                                            {
                                            case CommandTypes.Alias:
                                                this._current_5__14 = new AliasInfo(this._entry_5__13.Value.Name, null, this.context);
                                                break;

                                            case CommandTypes.Function:
                                                this._current_5__14 = new FunctionInfo(this._entry_5__13.Value.Name, ScriptBlock.Create(""), this.context);
                                                break;

                                            case CommandTypes.Filter:
                                                this._current_5__14 = new FilterInfo(this._entry_5__13.Value.Name, ScriptBlock.Create(""), this.context);
                                                break;

                                            case CommandTypes.Cmdlet:
                                                this._current_5__14 = new CmdletInfo(this._entry_5__13.Value.Name, null, null, null, this.context);
                                                break;

                                            case CommandTypes.Workflow:
                                                this._current_5__14 = new WorkflowInfo(this._entry_5__13.Value.Name, ScriptBlock.Create(""), this.context);
                                                break;
                                            }
                                            this._current_5__14.SetModule(this._tempModuleInfo_5__11);
                                            this.__2__current = this._current_5__14;
                                            this.__1__state   = 3;
                                            return(true);

                                            this.__1__state = 2;
                                        }
                                        this.__m__Finally1e();
                                        continue;
                                    }
                                }
                                this._moduleShortName_5__15  = Path.GetFileNameWithoutExtension(this._modulePath_5__e);
                                this._exportedCommands_5__16 = AnalysisCache.GetExportedCommands(this._modulePath_5__e, false, this.context);
                                if (this._exportedCommands_5__16 != null)
                                {
                                    this._tempModuleInfo_5__11 = new PSModuleInfo(this._moduleShortName_5__15, this._modulePath_5__e, null, null);
                                    if (InitialSessionState.IsEngineModule(this._moduleShortName_5__15))
                                    {
                                        this._tempModuleInfo_5__11.SetModuleBase(Utils.GetApplicationBase(Utils.DefaultPowerShellShellID));
                                    }
                                    this.__7__wrap1f = this._exportedCommands_5__16.Keys.GetEnumerator();
                                    this.__1__state  = 4;
                                    while (this.__7__wrap1f.MoveNext())
                                    {
                                        this._exportedCommand_5__17 = this.__7__wrap1f.Current;
                                        if (this._commandPattern_5__b.IsMatch(this._exportedCommand_5__17))
                                        {
                                            this.__7__wrap21 = this._exportedCommands_5__16[this._exportedCommand_5__17].GetEnumerator();
                                            this.__1__state  = 5;
                                            while (this.__7__wrap21.MoveNext())
                                            {
                                                this._commandType_5__18         = this.__7__wrap21.Current;
                                                this._shouldExportCommand_5__19 = true;
                                                if ((this.context.InitialSessionState != null) && (this.commandOrigin == CommandOrigin.Runspace))
                                                {
                                                    foreach (SessionStateCommandEntry entry in this.context.InitialSessionState.Commands[this._exportedCommand_5__17])
                                                    {
                                                        string b = null;
                                                        if (entry.Module != null)
                                                        {
                                                            b = entry.Module.Name;
                                                        }
                                                        else if (entry.PSSnapIn != null)
                                                        {
                                                            b = entry.PSSnapIn.Name;
                                                        }
                                                        if (string.Equals(this._moduleShortName_5__15, b, StringComparison.OrdinalIgnoreCase) && (entry.Visibility == SessionStateEntryVisibility.Private))
                                                        {
                                                            this._shouldExportCommand_5__19 = false;
                                                        }
                                                    }
                                                }
                                                if (!this._shouldExportCommand_5__19)
                                                {
                                                    continue;
                                                }
                                                this._current_5__1a = null;
                                                switch (this._commandType_5__18)
                                                {
                                                case CommandTypes.Alias:
                                                    this._current_5__1a = new AliasInfo(this._exportedCommand_5__17, null, this.context);
                                                    break;

                                                case CommandTypes.Function:
                                                    this._current_5__1a = new FunctionInfo(this._exportedCommand_5__17, ScriptBlock.Create(""), this.context);
                                                    break;

                                                case CommandTypes.Cmdlet:
                                                    this._current_5__1a = new CmdletInfo(this._exportedCommand_5__17, null, null, null, this.context);
                                                    break;

                                                case CommandTypes.Workflow:
                                                    this._current_5__1a = new WorkflowInfo(this._exportedCommand_5__17, ScriptBlock.Create(""), this.context);
                                                    break;
                                                }
                                                if (this._current_5__1a != null)
                                                {
                                                    this._current_5__1a.SetModule(this._tempModuleInfo_5__11);
                                                }
                                                this.__2__current = this._current_5__1a;
                                                this.__1__state   = 7;
                                                return(true);

Label_060F:
                                                this.__1__state = 5;
                                            }
                                            this.__m__Finally22();
                                        }
                                    }
                                    this.__m__Finally20();
                                }
                            }
                            this.__m__Finally1c();
                        }
                    }
                    return(false);
                }
                finally
                {
                    (this as IDisposable).Dispose();
                }
            }
Exemple #4
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);
                    }
                }
            }
        }