Exemplo n.º 1
0
        public override InitialSessionStateEntry Clone()
        {
            SessionStateFunctionEntry stateFunctionEntry = new SessionStateFunctionEntry(this.Name, this._definition, this._options, this.Visibility);

            stateFunctionEntry._scriptBlock = this._scriptBlock;
            stateFunctionEntry.SetModule(this.Module);
            return((InitialSessionStateEntry)stateFunctionEntry);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Add an new SessionState function entry to this session state object...
        /// </summary>
        /// <param name="entry">The entry to add.</param>
        internal void AddSessionStateEntry(SessionStateFunctionEntry entry)
        {
            ScriptBlock sb = entry.ScriptBlock.Clone();

            FunctionInfo fn = this.SetFunction(entry.Name, sb, null, entry.Options, false, CommandOrigin.Internal, this.ExecutionContext, entry.HelpFile, true);

            fn.Visibility = entry.Visibility;
            fn.Module     = entry.Module;
            fn.ScriptBlock.LanguageMode = entry.ScriptBlock.LanguageMode ?? PSLanguageMode.FullLanguage;
        }
Exemplo n.º 3
0
 /// <summary>
 /// Add all of the default built-in functions to this session state instance...
 /// </summary>
 internal void AddBuiltInEntries(bool addSetStrictMode)
 {
     // Other built-in variables
     AddBuiltInVariables();
     AddBuiltInFunctions();
     AddBuiltInAliases();
     if (addSetStrictMode)
     {
         SessionStateFunctionEntry f = new SessionStateFunctionEntry("Set-StrictMode", "");
         this.AddSessionStateEntry(f);
     }
 }
Exemplo n.º 4
0
 private bool DoesInitialSessionStateIncludeGetCommandWithListImportedSwitch()
 {
     if (!this._initialSessionStateIncludesGetCommandWithListImportedSwitch.HasValue)
     {
         lock (this._initialSessionStateIncludesGetCommandWithListImportedSwitchLock)
         {
             if (!this._initialSessionStateIncludesGetCommandWithListImportedSwitch.HasValue)
             {
                 bool flag = false;
                 InitialSessionState initialSessionState = this.RunspacePool.InitialSessionState;
                 if (initialSessionState != null)
                 {
                     IEnumerable <SessionStateCommandEntry> source = from entry in initialSessionState.Commands["Get-Command"]
                                                                     where entry.Visibility == SessionStateEntryVisibility.Public
                                                                     select entry;
                     SessionStateFunctionEntry e = source.OfType <SessionStateFunctionEntry>().FirstOrDefault <SessionStateFunctionEntry>();
                     if (e != null)
                     {
                         if (e.ScriptBlock.ParameterMetadata.BindableParameters.ContainsKey("ListImported"))
                         {
                             flag = true;
                         }
                     }
                     else
                     {
                         SessionStateCmdletEntry entry2 = source.OfType <SessionStateCmdletEntry>().FirstOrDefault <SessionStateCmdletEntry>();
                         if ((entry2 != null) && entry2.ImplementingType.Equals(typeof(GetCommandCommand)))
                         {
                             flag = true;
                         }
                     }
                 }
                 this._initialSessionStateIncludesGetCommandWithListImportedSwitch = new bool?(flag);
             }
         }
     }
     return(this._initialSessionStateIncludesGetCommandWithListImportedSwitch.Value);
 }
        private static List <string> GetSingleAstRequiredModules(Ast ast, Token[] tokens)
        {
            List <string> modules   = new List <string>();
            List <string> resources = new List <string>();
            var           imports   = tokens.Where(token =>
                                                   String.Compare(token.Text, "Import-DscResource", StringComparison.OrdinalIgnoreCase) == 0);

            //
            // Create a function with the same name as Import-DscResource keyword and use powershell
            // argument function binding to emulate Import-DscResource argument binding.
            //
            InitialSessionState       initialSessionState            = InitialSessionState.Create();
            SessionStateFunctionEntry importDscResourcefunctionEntry = new SessionStateFunctionEntry(
                "Import-DscResource", @"param($Name, $ModuleName)
                if ($ModuleName) 
                {
                    foreach ($m in $ModuleName) { $global:modules.Add($m) }
                } else {
                    foreach ($n in $Name) { $global:resources.Add($n) }
                }
            ");

            initialSessionState.Commands.Add(importDscResourcefunctionEntry);
            initialSessionState.LanguageMode = PSLanguageMode.RestrictedLanguage;
            var moduleVarEntry    = new SessionStateVariableEntry("modules", modules, "");
            var resourcesVarEntry = new SessionStateVariableEntry("resources", resources, "");

            initialSessionState.Variables.Add(moduleVarEntry);
            initialSessionState.Variables.Add(resourcesVarEntry);

            using (System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create(initialSessionState))
            {
                foreach (var import in imports)
                {
                    int startOffset      = import.Extent.StartOffset;
                    var asts             = ast.FindAll(a => IsCandidateForImportDscResourceAst(a, startOffset), true);
                    int longestLen       = -1;
                    Ast longestCandidate = null;
                    foreach (var candidatAst in asts)
                    {
                        int curLen = candidatAst.Extent.EndOffset - candidatAst.Extent.StartOffset;
                        if (curLen > longestLen)
                        {
                            longestCandidate = candidatAst;
                            longestLen       = curLen;
                        }
                    }
                    // longestCandidate should contain AST for import-dscresource, like "Import-DSCResource -Module x -Name y".
                    if (longestCandidate != null)
                    {
                        string importText = longestCandidate.Extent.Text;
                        // We invoke-command "importText" here. Script injection is prevented:
                        // We checked that file represents a valid AST without errors.
                        powerShell.AddScript(importText);
                        powerShell.Invoke();
                        powerShell.Commands.Clear();
                    }
                }
            }
            modules.AddRange(resources.Select(GetModuleNameForDscResource));
            return(modules);
        }
Exemplo n.º 6
0
        public static InitialSessionState GetSessionStateForCommands(CommandInfo[] commands)
        {
            InitialSessionState iss = InitialSessionState.CreateDefault();
            Dictionary <string, SessionStateCommandEntry> commandCache = new Dictionary <string, SessionStateCommandEntry>();

            foreach (SessionStateCommandEntry ssce in iss.Commands)
            {
                commandCache[ssce.Name] = ssce;
            }
            iss.ApartmentState = ApartmentState.STA;
            iss.ThreadOptions  = PSThreadOptions.ReuseThread;
            if (commands.Length == 0)
            {
                return(iss);
            }
            foreach (CommandInfo cmd in commands)
            {
                if (cmd.Module != null)
                {
                    string manifestPath = cmd.Module.Path.Replace(".psm1", ".psd1").Replace(".dll", ".psd1");
                    if (System.IO.File.Exists(manifestPath))
                    {
                        iss.ImportPSModule(new string[] { manifestPath });
                    }
                    else
                    {
                        iss.ImportPSModule(new string[] { cmd.Module.Path });
                    }

                    continue;
                }
                if (cmd is AliasInfo)
                {
                    CommandInfo loopCommand = cmd;
                    while (loopCommand is AliasInfo)
                    {
                        SessionStateAliasEntry alias = new SessionStateAliasEntry(loopCommand.Name, loopCommand.Definition);
                        iss.Commands.Add(alias);
                        loopCommand = (loopCommand as AliasInfo).ReferencedCommand;
                    }
                    if (loopCommand is FunctionInfo)
                    {
                        SessionStateFunctionEntry func = new SessionStateFunctionEntry(loopCommand.Name, loopCommand.Definition);
                        iss.Commands.Add(func);
                    }
                    if (loopCommand is CmdletInfo)
                    {
                        CmdletInfo cmdletData          = loopCommand as CmdletInfo;
                        SessionStateCmdletEntry cmdlet = new SessionStateCmdletEntry(cmd.Name,
                                                                                     cmdletData.ImplementingType,
                                                                                     cmdletData.HelpFile);
                        iss.Commands.Add(cmdlet);
                    }
                }
                if (cmd is FunctionInfo)
                {
                    SessionStateFunctionEntry func = new SessionStateFunctionEntry(cmd.Name, cmd.Definition);
                    iss.Commands.Add(func);
                }
                if (cmd is CmdletInfo)
                {
                    CmdletInfo cmdletData          = cmd as CmdletInfo;
                    SessionStateCmdletEntry cmdlet = new SessionStateCmdletEntry(cmd.Name,
                                                                                 cmdletData.ImplementingType,
                                                                                 cmdletData.HelpFile);
                    iss.Commands.Add(cmdlet);
                }
            }
            return(iss);
        }
Exemplo n.º 7
0
        public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo)
        {
            InitialSessionState state = null;
            bool        flag          = false;
            string      str           = TryGetValue(this.configHash, ConfigFileContants.SessionType);
            SessionType type          = SessionType.Default;
            bool        flag2         = this.IsNonDefaultVisibiltySpecified(ConfigFileContants.VisibleCmdlets);
            bool        flag3         = this.IsNonDefaultVisibiltySpecified(ConfigFileContants.VisibleFunctions);
            bool        flag4         = this.IsNonDefaultVisibiltySpecified(ConfigFileContants.VisibleAliases);
            bool        flag5         = this.IsNonDefaultVisibiltySpecified(ConfigFileContants.VisibleProviders);

            if (!string.IsNullOrEmpty(str))
            {
                type = (SessionType)Enum.Parse(typeof(SessionType), str, true);
                switch (type)
                {
                case SessionType.Empty:
                    state = InitialSessionState.Create();
                    goto Label_00AD;

                case SessionType.RestrictedRemoteServer:
                    state = InitialSessionState.CreateRestricted(SessionCapabilities.RemoteServer);
                    if (flag5)
                    {
                        InitialSessionState state2 = InitialSessionState.CreateDefault2();
                        state.Providers.Add(state2.Providers);
                    }
                    goto Label_00AD;
                }
                state = InitialSessionState.CreateDefault2();
            }
            else
            {
                state = InitialSessionState.CreateDefault2();
            }
Label_00AD:
            if (this.configHash.ContainsKey(ConfigFileContants.AssembliesToLoad))
            {
                string[] strArray = TryGetStringArray(this.configHash[ConfigFileContants.AssembliesToLoad]);
                if (strArray != null)
                {
                    foreach (string str2 in strArray)
                    {
                        state.Assemblies.Add(new SessionStateAssemblyEntry(str2));
                    }
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.ModulesToImport))
            {
                object[] objArray = TryGetObjectsOfType <object>(this.configHash[ConfigFileContants.ModulesToImport], new Type[] { typeof(string), typeof(Hashtable) });
                if ((this.configHash[ConfigFileContants.ModulesToImport] != null) && (objArray == null))
                {
                    PSInvalidOperationException exception = new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringOrHashtableArray, ConfigFileContants.ModulesToImport));
                    exception.SetErrorId("InvalidModulesToImportKeyEntries");
                    throw exception;
                }
                if (objArray != null)
                {
                    Collection <ModuleSpecification> modules = new Collection <ModuleSpecification>();
                    foreach (object obj2 in objArray)
                    {
                        ModuleSpecification item = null;
                        string str4 = obj2 as string;
                        if (!string.IsNullOrEmpty(str4))
                        {
                            item = new ModuleSpecification(str4);
                        }
                        else
                        {
                            Hashtable moduleSpecification = obj2 as Hashtable;
                            if (moduleSpecification != null)
                            {
                                item = new ModuleSpecification(moduleSpecification);
                            }
                        }
                        if (item != null)
                        {
                            if (string.Equals(InitialSessionState.CoreModule, item.Name, StringComparison.OrdinalIgnoreCase))
                            {
                                if (type == SessionType.Empty)
                                {
                                    state.ImportCorePSSnapIn();
                                }
                            }
                            else
                            {
                                modules.Add(item);
                            }
                        }
                    }
                    state.ImportPSModule(modules);
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.AliasDefinitions))
            {
                Hashtable[] hashtableArray = TryGetHashtableArray(this.configHash[ConfigFileContants.AliasDefinitions]);
                if (hashtableArray != null)
                {
                    foreach (Hashtable hashtable2 in hashtableArray)
                    {
                        SessionStateAliasEntry entry = this.CreateSessionStateAliasEntry(hashtable2);
                        if (entry != null)
                        {
                            state.Commands.Add(entry);
                        }
                    }
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.FunctionDefinitions))
            {
                Hashtable[] hashtableArray2 = TryGetHashtableArray(this.configHash[ConfigFileContants.FunctionDefinitions]);
                if (hashtableArray2 != null)
                {
                    foreach (Hashtable hashtable3 in hashtableArray2)
                    {
                        SessionStateFunctionEntry entry2 = this.CreateSessionStateFunctionEntry(hashtable3);
                        if (entry2 != null)
                        {
                            state.Commands.Add(entry2);
                        }
                    }
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.VariableDefinitions))
            {
                Hashtable[] hashtableArray3 = TryGetHashtableArray(this.configHash[ConfigFileContants.VariableDefinitions]);
                if (hashtableArray3 != null)
                {
                    foreach (Hashtable hashtable4 in hashtableArray3)
                    {
                        if (!hashtable4.ContainsKey(ConfigFileContants.VariableValueToken) || !(hashtable4[ConfigFileContants.VariableValueToken] is ScriptBlock))
                        {
                            SessionStateVariableEntry entry3 = this.CreateSessionStateVariableEntry(hashtable4);
                            if (entry3 != null)
                            {
                                state.Variables.Add(entry3);
                            }
                        }
                    }
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.TypesToProcess))
            {
                string[] strArray2 = TryGetStringArray(this.configHash[ConfigFileContants.TypesToProcess]);
                if (strArray2 != null)
                {
                    foreach (string str5 in strArray2)
                    {
                        if (!string.IsNullOrEmpty(str5))
                        {
                            state.Types.Add(new SessionStateTypeEntry(str5));
                        }
                    }
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.FormatsToProcess))
            {
                string[] strArray3 = TryGetStringArray(this.configHash[ConfigFileContants.FormatsToProcess]);
                if (strArray3 != null)
                {
                    foreach (string str6 in strArray3)
                    {
                        if (!string.IsNullOrEmpty(str6))
                        {
                            state.Formats.Add(new SessionStateFormatEntry(str6));
                        }
                    }
                }
            }
            if ((flag2 || flag3) || (flag4 || flag5))
            {
                flag = true;
            }
            if (flag)
            {
                state.Variables.Add(new SessionStateVariableEntry("PSModuleAutoLoadingPreference", PSModuleAutoLoadingPreference.None, string.Empty, ScopedItemOptions.None));
                if (type == SessionType.Default)
                {
                    state.ImportPSCoreModule(InitialSessionState.EngineModules.ToArray <string>());
                }
                if (!flag2)
                {
                    state.Commands.Remove("Import-Module", typeof(SessionStateCmdletEntry));
                }
                if (!flag4)
                {
                    state.Commands.Remove("ipmo", typeof(SessionStateAliasEntry));
                }
            }
            return(state);
        }