protected override void ProcessRecord()
        {
            ProviderInfo provider = null;
            PSDriveInfo  info2;
            FileStream   stream;
            StreamWriter writer;
            FileInfo     info3;
            string       filePath = base.SessionState.Path.GetUnresolvedProviderPathFromPSPath(this.path, out provider, out info2);

            if (!provider.NameEquals(base.Context.ProviderNames.FileSystem) || !filePath.EndsWith(".pssc", StringComparison.OrdinalIgnoreCase))
            {
                InvalidOperationException exception = new InvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.InvalidPSSessionConfigurationFilePath, this.path));
                ErrorRecord errorRecord             = new ErrorRecord(exception, "InvalidPSSessionConfigurationFilePath", ErrorCategory.InvalidArgument, this.path);
                base.ThrowTerminatingError(errorRecord);
            }
            PathUtils.MasterStreamOpen(this, filePath, "unicode", false, false, false, false, out stream, out writer, out info3, false);
            try
            {
                StringBuilder builder = new StringBuilder();
                builder.Append("@{");
                builder.Append(writer.NewLine);
                builder.Append(writer.NewLine);
                builder.Append(ConfigFragment(ConfigFileContants.SchemaVersion, RemotingErrorIdStrings.DISCSchemaVersionComment, QuoteName(this.schemaVersion.ToString()), writer));
                builder.Append(ConfigFragment(ConfigFileContants.Guid, RemotingErrorIdStrings.DISCGUIDComment, QuoteName(this.guid.ToString()), writer));
                builder.Append(ConfigFragment(ConfigFileContants.ExecutionPolicy, RemotingErrorIdStrings.DISCExecutionPolicyComment, QuoteName(this.executionPolicy), writer));
                if (!this.isLanguageModeSpecified && (this.initialSessionState == System.Management.Automation.Remoting.SessionType.Default))
                {
                    this.languageMode = PSLanguageMode.FullLanguage;
                }
                builder.Append(ConfigFragment(ConfigFileContants.LanguageMode, RemotingErrorIdStrings.DISCLanguageModeComment, QuoteName(this.languageMode), writer));
                builder.Append(ConfigFragment(ConfigFileContants.SessionType, RemotingErrorIdStrings.DISCInitialSessionStateComment, QuoteName(this.initialSessionState.ToString()), writer));
                if (this.environmentVariables == null)
                {
                    builder.Append(ConfigFragment(ConfigFileContants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment, string.Empty, writer));
                }
                else
                {
                    string environmentVariables = this.environmentVariables as string;
                    if (environmentVariables != null)
                    {
                        builder.Append(ConfigFragment(ConfigFileContants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment, environmentVariables, writer));
                    }
                    else
                    {
                        Hashtable table = this.environmentVariables as Hashtable;
                        if (table != null)
                        {
                            builder.Append(ConfigFragment(ConfigFileContants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment, this.CombineHashtable(table, writer), writer));
                        }
                        else
                        {
                            builder.Append(ConfigFragment(ConfigFileContants.EnvironmentVariables, RemotingErrorIdStrings.DISCEnvironmentVariablesComment, string.Empty, writer));
                        }
                    }
                }
                if (string.IsNullOrEmpty(this.author))
                {
                    this.author = Environment.UserName;
                }
                builder.Append(ConfigFragment(ConfigFileContants.Author, RemotingErrorIdStrings.DISCAuthorComment, QuoteName(this.author), writer));
                if (string.IsNullOrEmpty(this.companyName))
                {
                    this.companyName = Modules.DefaultCompanyName;
                }
                builder.Append(ConfigFragment(ConfigFileContants.CompanyName, RemotingErrorIdStrings.DISCCompanyNameComment, QuoteName(this.companyName), writer));
                if (string.IsNullOrEmpty(this.copyright))
                {
                    this.copyright = StringUtil.Format(Modules.DefaultCopyrightMessage, DateTime.Now.Year, this.author);
                }
                builder.Append(ConfigFragment(ConfigFileContants.Copyright, RemotingErrorIdStrings.DISCCopyrightComment, QuoteName(this.copyright), writer));
                builder.Append(ConfigFragment(ConfigFileContants.Description, RemotingErrorIdStrings.DISCDescriptionComment, string.IsNullOrEmpty(this.description) ? string.Empty : QuoteName(this.description), writer));
                builder.Append(ConfigFragment(ConfigFileContants.PowerShellVersion, RemotingErrorIdStrings.DISCPowerShellVersionComment, (this.powerShellVersion != null) ? QuoteName(this.powerShellVersion.ToString()) : string.Empty, writer));
                builder.Append(ConfigFragment(ConfigFileContants.ModulesToImport, RemotingErrorIdStrings.DISCModulesToImportComment, (this.modulesToImport != null) ? this.CombineHashTableOrStringArray(this.modulesToImport, writer) : string.Empty, writer));
                builder.Append(ConfigFragment(ConfigFileContants.AssembliesToLoad, RemotingErrorIdStrings.DISCAssembliesToLoadComment, (this.assembliesToLoad != null) ? this.CombineStringArray(this.assembliesToLoad) : string.Empty, writer));
                builder.Append(ConfigFragment(ConfigFileContants.VisibleAliases, RemotingErrorIdStrings.DISCVisibleAliasesComment, this.GetVisibilityDefault(this.visibleAliases), writer));
                builder.Append(ConfigFragment(ConfigFileContants.VisibleCmdlets, RemotingErrorIdStrings.DISCVisibleCmdletsComment, this.GetVisibilityDefault(this.visibleCmdlets), writer));
                builder.Append(ConfigFragment(ConfigFileContants.VisibleFunctions, RemotingErrorIdStrings.DISCVisibleFunctionsComment, this.GetVisibilityDefault(this.visibleFunctions), writer));
                builder.Append(ConfigFragment(ConfigFileContants.VisibleProviders, RemotingErrorIdStrings.DISCVisibleProvidersComment, this.GetVisibilityDefault(this.visibleProviders), writer));
                builder.Append(ConfigFragment(ConfigFileContants.AliasDefinitions, RemotingErrorIdStrings.DISCAliasDefinitionsComment, (this.aliasDefinitions != null) ? this.CombineHashtableArray(this.aliasDefinitions, writer) : string.Empty, writer));
                if (this.functionDefinitions == null)
                {
                    builder.Append(ConfigFragment(ConfigFileContants.FunctionDefinitions, RemotingErrorIdStrings.DISCFunctionDefinitionsComment, string.Empty, writer));
                }
                else
                {
                    Hashtable[] tables = DISCPowerShellConfiguration.TryGetHashtableArray(this.functionDefinitions);
                    if (tables != null)
                    {
                        builder.Append(ConfigFragment(ConfigFileContants.FunctionDefinitions, RemotingErrorIdStrings.DISCFunctionDefinitionsComment, this.CombineHashtableArray(tables, writer), writer));
                        foreach (Hashtable hashtable2 in tables)
                        {
                            if (!hashtable2.ContainsKey(ConfigFileContants.FunctionNameToken))
                            {
                                PSArgumentException exception2 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, new object[] { ConfigFileContants.FunctionDefinitions, ConfigFileContants.FunctionNameToken, this.path }));
                                base.ThrowTerminatingError(exception2.ErrorRecord);
                            }
                            if (!hashtable2.ContainsKey(ConfigFileContants.FunctionValueToken))
                            {
                                PSArgumentException exception3 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, new object[] { ConfigFileContants.FunctionDefinitions, ConfigFileContants.FunctionValueToken, this.path }));
                                base.ThrowTerminatingError(exception3.ErrorRecord);
                            }
                            if (!(hashtable2[ConfigFileContants.FunctionValueToken] is ScriptBlock))
                            {
                                PSArgumentException exception4 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCKeyMustBeScriptBlock, new object[] { ConfigFileContants.FunctionValueToken, ConfigFileContants.FunctionDefinitions, this.path }));
                                base.ThrowTerminatingError(exception4.ErrorRecord);
                            }
                            foreach (string str4 in hashtable2.Keys)
                            {
                                if ((!string.Equals(str4, ConfigFileContants.FunctionNameToken, StringComparison.OrdinalIgnoreCase) && !string.Equals(str4, ConfigFileContants.FunctionValueToken, StringComparison.OrdinalIgnoreCase)) && !string.Equals(str4, ConfigFileContants.FunctionOptionsToken, StringComparison.OrdinalIgnoreCase))
                                {
                                    PSArgumentException exception5 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey, new object[] { str4, ConfigFileContants.FunctionDefinitions, this.path }));
                                    base.ThrowTerminatingError(exception5.ErrorRecord);
                                }
                            }
                        }
                    }
                    else
                    {
                        PSArgumentException exception6 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray, ConfigFileContants.FunctionDefinitions, filePath));
                        base.ThrowTerminatingError(exception6.ErrorRecord);
                    }
                }
                if (this.variableDefinitions == null)
                {
                    builder.Append(ConfigFragment(ConfigFileContants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment, string.Empty, writer));
                }
                else
                {
                    string variableDefinitions = this.variableDefinitions as string;
                    if (variableDefinitions != null)
                    {
                        builder.Append(ConfigFragment(ConfigFileContants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment, variableDefinitions, writer));
                    }
                    else
                    {
                        Hashtable[] hashtableArray2 = DISCPowerShellConfiguration.TryGetHashtableArray(this.variableDefinitions);
                        if (hashtableArray2 != null)
                        {
                            builder.Append(ConfigFragment(ConfigFileContants.VariableDefinitions, RemotingErrorIdStrings.DISCVariableDefinitionsComment, this.CombineHashtableArray(hashtableArray2, writer), writer));
                            foreach (Hashtable hashtable3 in hashtableArray2)
                            {
                                if (!hashtable3.ContainsKey(ConfigFileContants.VariableNameToken))
                                {
                                    PSArgumentException exception7 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, new object[] { ConfigFileContants.VariableDefinitions, ConfigFileContants.VariableNameToken, this.path }));
                                    base.ThrowTerminatingError(exception7.ErrorRecord);
                                }
                                if (!hashtable3.ContainsKey(ConfigFileContants.VariableValueToken))
                                {
                                    PSArgumentException exception8 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustContainKey, new object[] { ConfigFileContants.VariableDefinitions, ConfigFileContants.VariableValueToken, this.path }));
                                    base.ThrowTerminatingError(exception8.ErrorRecord);
                                }
                                foreach (string str6 in hashtable3.Keys)
                                {
                                    if (!string.Equals(str6, ConfigFileContants.VariableNameToken, StringComparison.OrdinalIgnoreCase) && !string.Equals(str6, ConfigFileContants.VariableValueToken, StringComparison.OrdinalIgnoreCase))
                                    {
                                        PSArgumentException exception9 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeContainsInvalidKey, new object[] { str6, ConfigFileContants.VariableDefinitions, this.path }));
                                        base.ThrowTerminatingError(exception9.ErrorRecord);
                                    }
                                }
                            }
                        }
                        else
                        {
                            PSArgumentException exception10 = new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeHashtableArray, ConfigFileContants.VariableDefinitions, filePath));
                            base.ThrowTerminatingError(exception10.ErrorRecord);
                        }
                    }
                }
                builder.Append(ConfigFragment(ConfigFileContants.TypesToProcess, RemotingErrorIdStrings.DISCTypesToProcessComment, (this.typesToProcess != null) ? this.CombineStringArray(this.typesToProcess) : string.Empty, writer));
                builder.Append(ConfigFragment(ConfigFileContants.FormatsToProcess, RemotingErrorIdStrings.DISCFormatsToProcessComment, (this.formatsToProcess != null) ? this.CombineStringArray(this.formatsToProcess) : string.Empty, writer));
                builder.Append(ConfigFragment(ConfigFileContants.ScriptsToProcess, RemotingErrorIdStrings.DISCScriptsToProcessComment, (this.scriptsToProcess != null) ? this.CombineStringArray(this.scriptsToProcess) : string.Empty, writer));
                builder.Append("}");
                builder.Append(writer.NewLine);
                builder.Append(writer.NewLine);
                writer.Write(builder.ToString());
            }
            finally
            {
                writer.Close();
            }
        }
Esempio n. 2
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);
                    }
                }
            }
        }
Esempio n. 3
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="createRunspaceEventArg"></param>
        /// <exception cref="InvalidOperationException">
        /// 1. InitialSessionState cannot be null.
        /// 2. Non existent InitialSessionState provider for the shellID
        /// </exception>
        private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createRunspaceEventArg)
        {
            if (createRunspaceEventArg == null)
            {
                throw PSTraceSource.NewArgumentNullException("createRunspaceEventArg");
            }
            RemoteDataObject<PSObject> rcvdData = createRunspaceEventArg.ReceivedData;
            Dbg.Assert(rcvdData != null, "rcvdData must be non-null");

            // set the PSSenderInfo sent in the first packets
            // This is used by the initial session state configuration providers like Exchange.
            if (Context != null)
            {
#if !CORECLR // TimeZone Not In CoreCLR
                _senderInfo.ClientTimeZone = Context.ClientCapability.TimeZone;
#endif
            }

            _senderInfo.ApplicationArguments = RemotingDecoder.GetApplicationArguments(rcvdData.Data);

            // Get Initial Session State from custom session config suppliers
            // like Exchange.
            ConfigurationDataFromXML configurationData =
                PSSessionConfiguration.LoadEndPointConfiguration(_configProviderId,
                    _initParameters);
            // used by Out-Of-Proc (IPC) runspace.
            configurationData.InitializationScriptForOutOfProcessRunspace = _initScriptForOutOfProcRS;
            // start with data from configuration XML and then override with data
            // from EndPointConfiguration type.
            _maxRecvdObjectSize = configurationData.MaxReceivedObjectSizeMB;
            _maxRecvdDataSizeCommand = configurationData.MaxReceivedCommandSizeMB;

            DISCPowerShellConfiguration discProvider = null;

            if (String.IsNullOrEmpty(configurationData.ConfigFilePath))
            {
                _sessionConfigProvider = configurationData.CreateEndPointConfigurationInstance();
            }
            else
            {
                System.Security.Principal.WindowsPrincipal windowsPrincipal = new System.Security.Principal.WindowsPrincipal(_senderInfo.UserInfo.WindowsIdentity);

                Func<string, bool> validator = (role) => windowsPrincipal.IsInRole(role);

                discProvider = new DISCPowerShellConfiguration(configurationData.ConfigFilePath, validator);
                _sessionConfigProvider = discProvider;
            }

            // exchange of ApplicationArguments and ApplicationPrivateData is be done as early as possible
            // (i.e. to let the _sessionConfigProvider bail out if it can't comply with client's versioning request)
            PSPrimitiveDictionary applicationPrivateData = _sessionConfigProvider.GetApplicationPrivateData(_senderInfo);

            InitialSessionState rsSessionStateToUse = null;

            if (configurationData.SessionConfigurationData != null)
            {
                try
                {
                    rsSessionStateToUse =
                        _sessionConfigProvider.GetInitialSessionState(configurationData.SessionConfigurationData, _senderInfo, _configProviderId);
                }
                catch (NotImplementedException)
                {
                    rsSessionStateToUse = _sessionConfigProvider.GetInitialSessionState(_senderInfo);
                }
            }
            else
            {
                rsSessionStateToUse = _sessionConfigProvider.GetInitialSessionState(_senderInfo);
            }

            if (null == rsSessionStateToUse)
            {
                throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.InitialSessionStateNull, _configProviderId);
            }

            rsSessionStateToUse.ThrowOnRunspaceOpenError = true;

            // this might throw if the sender info is already present
            rsSessionStateToUse.Variables.Add(
                new SessionStateVariableEntry(RemoteDataNameStrings.SenderInfoPreferenceVariable,
                _senderInfo,
                Remoting.PSRemotingErrorInvariants.FormatResourceString(
                    RemotingErrorIdStrings.PSSenderInfoDescription),
                ScopedItemOptions.ReadOnly));

            // check if the current scenario is Win7(client) to Win8(server). Add back the PSv2 version TabExpansion
            // function if necessary.
            Version psClientVersion = null;
            if (_senderInfo.ApplicationArguments != null && _senderInfo.ApplicationArguments.ContainsKey("PSversionTable"))
            {
                var value = PSObject.Base(_senderInfo.ApplicationArguments["PSversionTable"]) as PSPrimitiveDictionary;
                if (value != null)
                {
                    if (value.ContainsKey("WSManStackVersion"))
                    {
                        var wsmanStackVersion = PSObject.Base(value["WSManStackVersion"]) as Version;
                        if (wsmanStackVersion != null && wsmanStackVersion.Major < 3)
                        {
                            // The client side is PSv2. This is the Win7 to Win8 scenario. We need to add the PSv2 
                            // TabExpansion function back in to keep the tab expansion functionable on the client side.
                            rsSessionStateToUse.Commands.Add(
                                new SessionStateFunctionEntry(
                                    RemoteDataNameStrings.PSv2TabExpansionFunction,
                                    RemoteDataNameStrings.PSv2TabExpansionFunctionText));
                        }
                    }
                    if (value.ContainsKey("PSVersion"))
                    {
                        psClientVersion = PSObject.Base(value["PSVersion"]) as Version;
                    }
                }
            }

            if (!string.IsNullOrEmpty(configurationData.EndPointConfigurationTypeName))
            {
                // user specified a type to load for configuration..use the values from this type.
                _maxRecvdObjectSize = _sessionConfigProvider.GetMaximumReceivedObjectSize(_senderInfo);
                _maxRecvdDataSizeCommand = _sessionConfigProvider.GetMaximumReceivedDataSizePerCommand(_senderInfo);
            }
            SessionDataStructureHandler.TransportManager.ReceivedDataCollection.MaximumReceivedObjectSize = _maxRecvdObjectSize;
            // MaximumReceivedDataSize is not set for session transport manager...see the constructor
            // for more info.

            Guid clientRunspacePoolId = rcvdData.RunspacePoolId;
            int minRunspaces = RemotingDecoder.GetMinRunspaces(rcvdData.Data);
            int maxRunspaces = RemotingDecoder.GetMaxRunspaces(rcvdData.Data);
            PSThreadOptions threadOptions = RemotingDecoder.GetThreadOptions(rcvdData.Data);
#if !CORECLR // No ApartmentState In CoreCLR
            ApartmentState apartmentState = RemotingDecoder.GetApartmentState(rcvdData.Data);
#endif
            HostInfo hostInfo = RemotingDecoder.GetHostInfo(rcvdData.Data);

            if (_runspacePoolDriver != null)
            {
                throw new PSRemotingDataStructureException(RemotingErrorIdStrings.RunspaceAlreadyExists,
                    _runspacePoolDriver.InstanceId);
            }

#if !UNIX
            bool isAdministrator = _senderInfo.UserInfo.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
#else
            bool isAdministrator = false;
#endif

            ServerRunspacePoolDriver tmpDriver = new ServerRunspacePoolDriver(
                clientRunspacePoolId,
                minRunspaces,
                maxRunspaces,
                threadOptions,
#if !CORECLR // No ApartmentState In CoreCLR
                apartmentState,
#endif
                hostInfo,
                rsSessionStateToUse,
                applicationPrivateData,
                configurationData,
                this.SessionDataStructureHandler.TransportManager,
                isAdministrator,
                Context.ServerCapability,
                psClientVersion,
                _configurationName);

            // attach the necessary event handlers and start the driver.
            Interlocked.Exchange(ref _runspacePoolDriver, tmpDriver);
            _runspacePoolDriver.Closed += HandleResourceClosing;
            _runspacePoolDriver.Start();
        }
Esempio n. 4
0
        private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createRunspaceEventArg)
        {
            if (createRunspaceEventArg == null)
            {
                throw PSTraceSource.NewArgumentNullException("createRunspaceEventArg");
            }
            RemoteDataObject<PSObject> receivedData = createRunspaceEventArg.ReceivedData;
            if (this._context != null)
            {
				if (this._context.ClientCapability == null) {
					this._senderInfo.ClientTimeZone = this._context.ServerCapability.TimeZone;
				}
				else {
					this._senderInfo.ClientTimeZone = this._context.ClientCapability.TimeZone;
				}
            }
            this._senderInfo.ApplicationArguments = RemotingDecoder.GetApplicationArguments(receivedData.Data);
            ConfigurationDataFromXML configData = PSSessionConfiguration.LoadEndPointConfiguration(this._configProviderId, this._initParameters);
            configData.InitializationScriptForOutOfProcessRunspace = this._initScriptForOutOfProcRS;
            this.maxRecvdObjectSize = configData.MaxReceivedObjectSizeMB;
            this.maxRecvdDataSizeCommand = configData.MaxReceivedCommandSizeMB;
            DISCPowerShellConfiguration configuration = null;
            if (string.IsNullOrEmpty(configData.ConfigFilePath))
            {
                this._sessionConfigProvider = configData.CreateEndPointConfigurationInstance();
            }
            else
            {
                configuration = new DISCPowerShellConfiguration(configData.ConfigFilePath);
                this._sessionConfigProvider = configuration;
            }
            PSPrimitiveDictionary applicationPrivateData = this._sessionConfigProvider.GetApplicationPrivateData(this._senderInfo);
            InitialSessionState initialSessionState = null;
            if (configData.SessionConfigurationData != null)
            {
                try
                {
                    initialSessionState = this._sessionConfigProvider.GetInitialSessionState(configData.SessionConfigurationData, this._senderInfo, this._configProviderId);
                }
                catch (NotImplementedException)
                {
                    initialSessionState = this._sessionConfigProvider.GetInitialSessionState(this._senderInfo);
                }
            }
            else
            {
                initialSessionState = this._sessionConfigProvider.GetInitialSessionState(this._senderInfo);
            }
            if (initialSessionState == null)
            {
                throw PSTraceSource.NewInvalidOperationException("RemotingErrorIdStrings", "InitialSessionStateNull", new object[] { this._configProviderId });
            }
            initialSessionState.ThrowOnRunspaceOpenError = true;
            initialSessionState.Variables.Add(new SessionStateVariableEntry("PSSenderInfo", this._senderInfo, PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.PSSenderInfoDescription, new object[0]), ScopedItemOptions.ReadOnly));
            if ((this._senderInfo.ApplicationArguments != null) && this._senderInfo.ApplicationArguments.ContainsKey("PSversionTable"))
            {
                PSPrimitiveDictionary dictionary2 = PSObject.Base(this._senderInfo.ApplicationArguments["PSversionTable"]) as PSPrimitiveDictionary;
                if ((dictionary2 != null) && dictionary2.ContainsKey("WSManStackVersion"))
                {
                    Version version = PSObject.Base(dictionary2["WSManStackVersion"]) as Version;
                    if ((version != null) && (version.Major < 3))
                    {
                        initialSessionState.Commands.Add(new SessionStateFunctionEntry("TabExpansion", "\r\n            param($line, $lastWord)\r\n            & {\r\n                function Write-Members ($sep='.')\r\n                {\r\n                    Invoke-Expression ('$_val=' + $_expression)\r\n\r\n                    $_method = [Management.Automation.PSMemberTypes] `\r\n                        'Method,CodeMethod,ScriptMethod,ParameterizedProperty'\r\n                    if ($sep -eq '.')\r\n                    {\r\n                        $params = @{view = 'extended','adapted','base'}\r\n                    }\r\n                    else\r\n                    {\r\n                        $params = @{static=$true}\r\n                    }\r\n        \r\n                    foreach ($_m in ,$_val | Get-Member @params $_pat |\r\n                        Sort-Object membertype,name)\r\n                    {\r\n                        if ($_m.MemberType -band $_method)\r\n                        {\r\n                            # Return a method...\r\n                            $_base + $_expression + $sep + $_m.name + '('\r\n                        }\r\n                        else {\r\n                            # Return a property...\r\n                            $_base + $_expression + $sep + $_m.name\r\n                        }\r\n                    }\r\n                }\r\n\r\n                # If a command name contains any of these chars, it needs to be quoted\r\n                $_charsRequiringQuotes = ('`&@''#{}()$,;|<> ' + \"`t\").ToCharArray()\r\n\r\n                # If a variable name contains any of these characters it needs to be in braces\r\n                $_varsRequiringQuotes = ('-`&@''#{}()$,;|<> .\\/' + \"`t\").ToCharArray()\r\n\r\n                switch -regex ($lastWord)\r\n                {\r\n                    # Handle property and method expansion rooted at variables...\r\n                    # e.g. $a.b.<tab>\r\n                    '(^.*)(\\$(\\w|:|\\.)+)\\.([*\\w]*)$' {\r\n                        $_base = $matches[1]\r\n                        $_expression = $matches[2]\r\n                        $_pat = $matches[4] + '*'\r\n                        Write-Members\r\n                        break;\r\n                    }\r\n\r\n                    # Handle simple property and method expansion on static members...\r\n                    # e.g. [datetime]::n<tab>\r\n                    '(^.*)(\\[(\\w|\\.|\\+)+\\])(\\:\\:|\\.){0,1}([*\\w]*)$' {\r\n                        $_base = $matches[1]\r\n                        $_expression = $matches[2]\r\n                        $_pat = $matches[5] + '*'\r\n                        Write-Members $(if (! $matches[4]) {'::'} else {$matches[4]})\r\n                        break;\r\n                    }\r\n\r\n                    # Handle complex property and method expansion on static members\r\n                    # where there are intermediate properties...\r\n                    # e.g. [datetime]::now.d<tab>\r\n                    '(^.*)(\\[(\\w|\\.|\\+)+\\](\\:\\:|\\.)(\\w+\\.)+)([*\\w]*)$' {\r\n                        $_base = $matches[1]  # everything before the expression\r\n                        $_expression = $matches[2].TrimEnd('.') # expression less trailing '.'\r\n                        $_pat = $matches[6] + '*'  # the member to look for...\r\n                        Write-Members\r\n                        break;\r\n                    }\r\n\r\n                    # Handle variable name expansion...\r\n                    '(^.*\\$)([*\\w:]+)$' {\r\n                        $_prefix = $matches[1]\r\n                        $_varName = $matches[2]\r\n                        $_colonPos = $_varname.IndexOf(':')\r\n                        if ($_colonPos -eq -1)\r\n                        {\r\n                            $_varName = 'variable:' + $_varName\r\n                            $_provider = ''\r\n                        }\r\n                        else\r\n                        {\r\n                            $_provider = $_varname.Substring(0, $_colonPos+1)\r\n                        }\r\n\r\n                        foreach ($_v in Get-ChildItem ($_varName + '*') | sort Name)\r\n                        { \r\n                            $_nameFound = $_v.name\r\n                            $(if ($_nameFound.IndexOfAny($_varsRequiringQuotes) -eq -1) {'{0}{1}{2}'}\r\n                            else {'{0}{{{1}{2}}}'}) -f $_prefix, $_provider, $_nameFound\r\n                        }\r\n                        break;\r\n                    }\r\n\r\n                    # Do completion on parameters...\r\n                    '^-([*\\w0-9]*)' {\r\n                        $_pat = $matches[1] + '*'\r\n\r\n                        # extract the command name from the string\r\n                        # first split the string into statements and pipeline elements\r\n                        # This doesn't handle strings however.\r\n                        $_command = [regex]::Split($line, '[|;=]')[-1]\r\n\r\n                        #  Extract the trailing unclosed block e.g. ls | foreach { cp\r\n                        if ($_command -match '\\{([^\\{\\}]*)$')\r\n                        {\r\n                            $_command = $matches[1]\r\n                        }\r\n\r\n                        # Extract the longest unclosed parenthetical expression...\r\n                        if ($_command -match '\\(([^()]*)$')\r\n                        {\r\n                            $_command = $matches[1]\r\n                        }\r\n\r\n                        # take the first space separated token of the remaining string\r\n                        # as the command to look up. Trim any leading or trailing spaces\r\n                        # so you don't get leading empty elements.\r\n                        $_command = $_command.TrimEnd('-')\r\n                        $_command,$_arguments = $_command.Trim().Split()\r\n\r\n                        # now get the info object for it, -ArgumentList will force aliases to be resolved\r\n                        # it also retrieves dynamic parameters\r\n                        try\r\n                        {\r\n                            $_command = @(Get-Command -type 'Alias,Cmdlet,Function,Filter,ExternalScript' `\r\n                                -Name $_command -ArgumentList $_arguments)[0]\r\n                        }\r\n                        catch\r\n                        {\r\n                            # see if the command is an alias. If so, resolve it to the real command\r\n                            if(Test-Path alias:\\$_command)\r\n                            {\r\n                                $_command = @(Get-Command -Type Alias $_command)[0].Definition\r\n                            }\r\n\r\n                            # If we were unsuccessful retrieving the command, try again without the parameters\r\n                            $_command = @(Get-Command -type 'Cmdlet,Function,Filter,ExternalScript' `\r\n                                -Name $_command)[0]\r\n                        }\r\n\r\n                        # remove errors generated by the command not being found, and break\r\n                        if(-not $_command) { $error.RemoveAt(0); break; }\r\n\r\n                        # expand the parameter sets and emit the matching elements\r\n                        # need to use psbase.Keys in case 'keys' is one of the parameters\r\n                        # to the cmdlet\r\n                        foreach ($_n in $_command.Parameters.psbase.Keys)\r\n                        {\r\n                            if ($_n -like $_pat) { '-' + $_n }\r\n                        }\r\n                        break;\r\n                    }\r\n\r\n                    # Tab complete against history either #<pattern> or #<id>\r\n                    '^#(\\w*)' {\r\n                        $_pattern = $matches[1]\r\n                        if ($_pattern -match '^[0-9]+$')\r\n                        {\r\n                            Get-History -ea SilentlyContinue -Id $_pattern | Foreach { $_.CommandLine } \r\n                        }\r\n                        else\r\n                        {\r\n                            $_pattern = '*' + $_pattern + '*'\r\n                            Get-History -Count 32767 | Sort-Object -Descending Id| Foreach { $_.CommandLine } | where { $_ -like $_pattern }\r\n                        }\r\n                        break;\r\n                    }\r\n\r\n                    # try to find a matching command...\r\n                    default {\r\n                        # parse the script...\r\n                        $_tokens = [System.Management.Automation.PSParser]::Tokenize($line,\r\n                            [ref] $null)\r\n\r\n                        if ($_tokens)\r\n                        {\r\n                            $_lastToken = $_tokens[$_tokens.count - 1]\r\n                            if ($_lastToken.Type -eq 'Command')\r\n                            {\r\n                                $_cmd = $_lastToken.Content\r\n\r\n                                # don't look for paths...\r\n                                if ($_cmd.IndexOfAny('/\\:') -eq -1)\r\n                                {\r\n                                    # handle parsing errors - the last token string should be the last\r\n                                    # string in the line...\r\n                                    if ($lastword.Length -ge $_cmd.Length -and \r\n                                        $lastword.substring($lastword.length-$_cmd.length) -eq $_cmd)\r\n                                    {\r\n                                        $_pat = $_cmd + '*'\r\n                                        $_base = $lastword.substring(0, $lastword.length-$_cmd.length)\r\n\r\n                                        # get files in current directory first, then look for commands...\r\n                                        $( try {Resolve-Path -ea SilentlyContinue -Relative $_pat } catch {} ;\r\n                                           try { $ExecutionContext.InvokeCommand.GetCommandName($_pat, $true, $false) |\r\n                                               Sort-Object -Unique } catch {} ) |\r\n                                                   # If the command contains non-word characters (space, ) ] ; ) etc.)\r\n                                                   # then it needs to be quoted and prefixed with &\r\n                                                   ForEach-Object {\r\n                                                        if ($_.IndexOfAny($_charsRequiringQuotes) -eq -1) { $_ }\r\n                                                        elseif ($_.IndexOf('''') -ge 0) {'& ''{0}''' -f $_.Replace('''','''''') }\r\n                                                        else { '& ''{0}''' -f $_ }} |\r\n                                                   ForEach-Object {'{0}{1}' -f $_base,$_ }\r\n                                    }\r\n                                }\r\n                            }\r\n                        }\r\n                    }\r\n                }\r\n            }\r\n        "));
                    }
                }
            }
            if (!string.IsNullOrEmpty(configData.EndPointConfigurationTypeName))
            {
                this.maxRecvdObjectSize = this._sessionConfigProvider.GetMaximumReceivedObjectSize(this._senderInfo);
                this.maxRecvdDataSizeCommand = this._sessionConfigProvider.GetMaximumReceivedDataSizePerCommand(this._senderInfo);
            }
            this._sessionDSHandler.TransportManager.ReceivedDataCollection.MaximumReceivedObjectSize = this.maxRecvdObjectSize;
            Guid runspacePoolId = receivedData.RunspacePoolId;
            int minRunspaces = RemotingDecoder.GetMinRunspaces(receivedData.Data);
            int maxRunspaces = RemotingDecoder.GetMaxRunspaces(receivedData.Data);
            PSThreadOptions threadOptions = RemotingDecoder.GetThreadOptions(receivedData.Data);
            ApartmentState apartmentState = RemotingDecoder.GetApartmentState(receivedData.Data);
            HostInfo hostInfo = RemotingDecoder.GetHostInfo(receivedData.Data);
            if (this._runspacePoolDriver != null)
            {
                throw new PSRemotingDataStructureException(RemotingErrorIdStrings.RunspaceAlreadyExists, new object[] { this._runspacePoolDriver.InstanceId });
            }
            bool isAdministrator = this._senderInfo.UserInfo.IsInRole(WindowsBuiltInRole.Administrator);
            ServerRunspacePoolDriver driver = new ServerRunspacePoolDriver(runspacePoolId, minRunspaces, maxRunspaces, threadOptions, apartmentState, hostInfo, initialSessionState, applicationPrivateData, configData, this.SessionDataStructureHandler.TransportManager, isAdministrator, this._context.ServerCapability, (configuration == null) ? null : configuration.ConfigHash);
            Interlocked.Exchange<ServerRunspacePoolDriver>(ref this._runspacePoolDriver, driver);
            this._runspacePoolDriver.Closed = (EventHandler<EventArgs>) Delegate.Combine(this._runspacePoolDriver.Closed, new EventHandler<EventArgs>(this.HandleResourceClosing));
            this._runspacePoolDriver.Start();
        }