Exemplo n.º 1
0
        private void UnzipHelpContent(System.Management.Automation.ExecutionContext context, string srcPath, string destPath)
        {
            if (!Directory.Exists(destPath))
            {
                Directory.CreateDirectory(destPath);
            }
            string directoryName = Path.GetDirectoryName(srcPath);

            if (!directoryName.EndsWith(@"\", StringComparison.Ordinal))
            {
                directoryName = directoryName + @"\";
            }
            if (!destPath.EndsWith(@"\", StringComparison.Ordinal))
            {
                destPath = destPath + @"\";
            }
            if (!CabinetExtractorFactory.GetCabinetExtractor().Extract(Path.GetFileName(srcPath), directoryName, destPath))
            {
                throw new UpdatableHelpSystemException("UnableToExtract", StringUtil.Format(HelpDisplayStrings.UnzipFailure, new object[0]), ErrorCategory.InvalidOperation, null, null);
            }
            foreach (string str2 in Directory.GetFiles(destPath))
            {
                if (System.IO.File.Exists(str2))
                {
                    FileInfo info = new FileInfo(str2);
                    if ((info.Attributes & System.IO.FileAttributes.ReadOnly) == System.IO.FileAttributes.ReadOnly)
                    {
                        info.Attributes &= ~System.IO.FileAttributes.ReadOnly;
                    }
                }
            }
        }
Exemplo n.º 2
0
 internal HtmlWebResponseObject(WebResponse response, MemoryStream contentStream, System.Management.Automation.ExecutionContext executionContext) : base(response, contentStream)
 {
     if (executionContext == null)
     {
         throw PSTraceSource.NewArgumentNullException("executionContext");
     }
     this._executionContext = executionContext;
     this.InitializeContent();
     this.InitializeRawContent(response);
 }
Exemplo n.º 3
0
 internal HtmlWebResponseObject(WebResponse response, MemoryStream contentStream, System.Management.Automation.ExecutionContext executionContext) : base(response, contentStream)
 {
     if (executionContext == null)
     {
         throw PSTraceSource.NewArgumentNullException("executionContext");
     }
     this._executionContext = executionContext;
     this.InitializeContent();
     this.InitializeRawContent(response);
 }
        /// <summary>
        /// Constructor for HtmlWebResponseObject with memory stream
        /// </summary>
        /// <param name="response"></param>
        /// <param name="contentStream"></param>
        /// <param name="executionContext"></param>
        internal HtmlWebResponseObject(WebResponse response, Stream contentStream, ExecutionContext executionContext)
            : base(response, contentStream)
        {
            if (executionContext == null)
            {
                throw PSTraceSource.NewArgumentNullException("executionContext");
            }

            _executionContext = executionContext;
            InitializeContent();
            InitializeRawContent(response);
        }
        /// <summary>
        /// Constructor for HtmlWebResponseObject with memory stream
        /// </summary>
        /// <param name="response"></param>
        /// <param name="contentStream"></param>        
        /// <param name="executionContext"></param>
        internal HtmlWebResponseObject(WebResponse response, Stream contentStream, ExecutionContext executionContext)
            : base(response, contentStream)
        {
            if (executionContext == null)
            {
                throw PSTraceSource.NewArgumentNullException("executionContext");
            }

            _executionContext = executionContext;
            InitializeContent();
            InitializeRawContent(response);
        }
Exemplo n.º 6
0
 internal void InstallHelpContent(UpdatableHelpCommandType commandType, System.Management.Automation.ExecutionContext context, string sourcePath, Collection <string> destPaths, string fileName, string tempPath, CultureInfo culture, string xsdPath, out Collection <string> installed)
 {
     if (this._stopping)
     {
         installed = new Collection <string>();
     }
     else
     {
         if (!Directory.Exists(tempPath))
         {
             Directory.CreateDirectory(tempPath);
         }
         try
         {
             this.OnProgressChanged(this, new UpdatableHelpProgressEventArgs(this._currentModule, commandType, StringUtil.Format(HelpDisplayStrings.UpdateProgressInstalling, new object[0]), 0));
             string path = Path.Combine(sourcePath, fileName);
             if (!System.IO.File.Exists(path))
             {
                 throw new UpdatableHelpSystemException("HelpContentNotFound", StringUtil.Format(HelpDisplayStrings.HelpContentNotFound, new object[0]), ErrorCategory.ResourceUnavailable, null, null);
             }
             string str2 = Path.Combine(tempPath, Path.GetFileNameWithoutExtension(fileName));
             if (Directory.Exists(str2))
             {
                 Directory.Delete(str2, true);
             }
             this.UnzipHelpContent(context, path, str2);
             this.ValidateAndCopyHelpContent(str2, destPaths, culture.Name, xsdPath, out installed);
         }
         finally
         {
             this.OnProgressChanged(this, new UpdatableHelpProgressEventArgs(this._currentModule, commandType, StringUtil.Format(HelpDisplayStrings.UpdateProgressInstalling, new object[0]), 100));
             try
             {
                 if (Directory.Exists(tempPath))
                 {
                     Directory.Delete(tempPath);
                 }
             }
             catch (IOException)
             {
             }
             catch (UnauthorizedAccessException)
             {
             }
             catch (ArgumentException)
             {
             }
         }
     }
 }
Exemplo n.º 7
0
        internal History(System.Management.Automation.ExecutionContext context)
        {
            Collection <Attribute> attributes = new Collection <Attribute> {
                new ValidateRangeAttribute(1, 0x7fff)
            };
            PSVariable variable = new PSVariable("MaximumHistoryCount", 0x1000, ScopedItemOptions.None, attributes)
            {
                Description = SessionStateStrings.MaxHistoryCountDescription
            };

            context.EngineSessionState.SetVariable(variable, false, CommandOrigin.Internal);
            this._capacity = 0x1000;
            this._buffer   = new HistoryInfo[this._capacity];
        }
Exemplo n.º 8
0
 internal History(System.Management.Automation.ExecutionContext context)
 {
     using (History._trace.TraceConstructor((object)this))
     {
         this._context = context;
         context.EngineSessionState.SetVariable(new PSVariable("MaximumHistoryCount", (object)64, ScopedItemOptions.None, new Collection <Attribute>()
         {
             (Attribute) new ValidateRangeAttribute((object)1, (object)(int)short.MaxValue)
         })
         {
             Description = ResourceManagerCache.GetResourceString("SessionStateStrings", "MaxHistoryCountDescription")
         }, false, CommandOrigin.Internal);
         this._capacity = 64;
         this._buffer   = new HistoryInfo[this._capacity];
     }
 }
Exemplo n.º 9
0
        private int GetHistorySize()
        {
            int num = 0;

            System.Management.Automation.ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();
            object valueToConvert = (executionContextFromTLS != null) ? executionContextFromTLS.GetVariableValue(SpecialVariables.HistorySizeVarPath) : null;

            if (valueToConvert != null)
            {
                try
                {
                    num = (int)LanguagePrimitives.ConvertTo(valueToConvert, typeof(int), CultureInfo.InvariantCulture);
                }
                catch (InvalidCastException)
                {
                }
            }
            if (num <= 0)
            {
                num = 0x1000;
            }
            return(num);
        }
Exemplo n.º 10
0
 public object GetValue(ExecutionContext context) => (object)null;
Exemplo n.º 11
0
 public IAssignableValue GetAssignableValue(
     Array input,
     ExecutionContext context)
 {
     return((IAssignableValue)this);
 }
Exemplo n.º 12
0
 /// <summary>
 /// Get using values in the array form.
 /// </summary>
 internal static object[] GetUsingValuesAsArray(ScriptBlock scriptBlock, bool isTrustedInput, ExecutionContext context, Dictionary <string, object> variables)
 {
     return(GetUsingValues(scriptBlock.Ast, isTrustedInput, context, variables, false).Item2);
 }
Exemplo n.º 13
0
 /// <summary>
 /// Constructor for HtmlWebResponseObject
 /// </summary>
 /// <param name="response"></param>
 /// <param name="executionContext"></param>
 internal HtmlWebResponseObject(WebResponse response, ExecutionContext executionContext)
     : this(response, null, executionContext)
 { }
 /// <summary>
 /// Constructor for HtmlWebResponseObject
 /// </summary>
 /// <param name="response"></param>
 /// <param name="executionContext"></param>
 internal HtmlWebResponseObject(WebResponse response, ExecutionContext executionContext)
     : this(response, null, executionContext)
 {
 }
Exemplo n.º 15
0
 /// <summary>
 /// Get current engine state for the engine instance corresponding to executionContext
 /// passed in.
 ///
 /// Engine state is stored in ExecutionContext.
 /// </summary>
 /// <param name="executionContext"></param>
 /// <returns></returns>
 private static EngineState GetEngineState(ExecutionContext executionContext)
 {
     return(executionContext.EngineState);
 }
Exemplo n.º 16
0
 /// <summary>
 /// This is a variation of basic LogEngineLifeCycleEvent api which makes invocationInfo
 /// optional.
 /// </summary>
 /// <param name="executionContext"></param>
 /// <param name="engineState"></param>
 internal static void LogEngineLifecycleEvent(ExecutionContext executionContext,
                                              EngineState engineState)
 {
     LogEngineLifecycleEvent(executionContext, engineState, null);
 }
Exemplo n.º 17
0
 /// <summary>
 /// This is a variation of LogEngineHealthEvent api to make eventid, additionalInfo and newEngineState
 /// optional.
 ///
 /// A default event id for engine health event will be used.
 /// </summary>
 /// <param name="executionContext"></param>
 /// <param name="exception"></param>
 /// <param name="severity"></param>
 internal static void LogEngineHealthEvent(ExecutionContext executionContext,
                                           Exception exception,
                                           Severity severity)
 {
     LogEngineHealthEvent(executionContext, 100, exception, severity, null);
 }
Exemplo n.º 18
0
        private void RunClause(Action <FunctionContext> clause, object dollarUnderbar, object inputToProcess)
        {
            ExecutionContext.CheckStackDepth();

            Pipe oldErrorOutputPipe = this.Context.ShellFunctionErrorOutputPipe;

            // If the script block has a different language mode than the current,
            // change the language mode.
            PSLanguageMode?oldLanguageMode = null;
            PSLanguageMode?newLanguageMode = null;

            if ((_scriptBlock.LanguageMode.HasValue) &&
                (_scriptBlock.LanguageMode != Context.LanguageMode))
            {
                oldLanguageMode = Context.LanguageMode;
                newLanguageMode = _scriptBlock.LanguageMode;
            }

            try
            {
                var oldScopeOrigin = this.Context.EngineSessionState.CurrentScope.ScopeOrigin;

                try
                {
                    this.Context.EngineSessionState.CurrentScope.ScopeOrigin =
                        this._dontUseScopeCommandOrigin ? CommandOrigin.Internal : this.Command.CommandOrigin;

                    // Set the language mode. We do this before EnterScope(), so that the language
                    // mode is appropriately applied for evaluation parameter defaults.
                    if (newLanguageMode.HasValue)
                    {
                        Context.LanguageMode = newLanguageMode.Value;
                    }

                    bool?oldLangModeTransitionStatus = null;
                    try
                    {
                        // If it's from ConstrainedLanguage to FullLanguage, indicate the transition before parameter binding takes place.
                        if (oldLanguageMode == PSLanguageMode.ConstrainedLanguage && newLanguageMode == PSLanguageMode.FullLanguage)
                        {
                            oldLangModeTransitionStatus = Context.LanguageModeTransitionInParameterBinding;
                            Context.LanguageModeTransitionInParameterBinding = true;
                        }

                        EnterScope();
                    }
                    finally
                    {
                        if (oldLangModeTransitionStatus.HasValue)
                        {
                            // Revert the transition state to old value after doing the parameter binding
                            Context.LanguageModeTransitionInParameterBinding = oldLangModeTransitionStatus.Value;
                        }
                    }

                    if (commandRuntime.ErrorMergeTo == MshCommandRuntime.MergeDataStream.Output)
                    {
                        Context.RedirectErrorPipe(commandRuntime.OutputPipe);
                    }
                    else if (commandRuntime.ErrorOutputPipe.IsRedirected)
                    {
                        Context.RedirectErrorPipe(commandRuntime.ErrorOutputPipe);
                    }

                    if (dollarUnderbar != AutomationNull.Value)
                    {
                        _localsTuple.SetAutomaticVariable(AutomaticVariable.Underbar, dollarUnderbar, _context);
                    }
                    else if (_dollarUnderbar != AutomationNull.Value)
                    {
                        _localsTuple.SetAutomaticVariable(AutomaticVariable.Underbar, _dollarUnderbar, _context);
                    }

                    if (inputToProcess != AutomationNull.Value)
                    {
                        if (inputToProcess == null)
                        {
                            inputToProcess = MshCommandRuntime.StaticEmptyArray.GetEnumerator();
                        }
                        else
                        {
                            IList list = inputToProcess as IList;
                            inputToProcess = (list != null)
                                                 ? list.GetEnumerator()
                                                 : LanguagePrimitives.GetEnumerator(inputToProcess);
                        }

                        _localsTuple.SetAutomaticVariable(AutomaticVariable.Input, inputToProcess, _context);
                    }

                    clause(_functionContext);
                }
                catch (TargetInvocationException tie)
                {
                    // DynamicInvoke wraps exceptions, unwrap them here.
                    throw tie.InnerException;
                }
                finally
                {
                    this.Context.RestoreErrorPipe(oldErrorOutputPipe);

                    if (oldLanguageMode.HasValue)
                    {
                        Context.LanguageMode = oldLanguageMode.Value;
                    }

                    Context.EngineSessionState.CurrentScope.ScopeOrigin = oldScopeOrigin;
                }
            }
            catch (ExitException ee)
            {
                if (!this.FromScriptFile || _rethrowExitException)
                {
                    throw;
                }

                this._exitWasCalled = true;

                int exitCode = (int)ee.Argument;
                this.Command.Context.SetVariable(SpecialVariables.LastExitCodeVarPath, exitCode);

                if (exitCode != 0)
                {
                    this.commandRuntime.PipelineProcessor.ExecutionFailed = true;
                }
            }
            catch (FlowControlException)
            {
                throw;
            }
            catch (RuntimeException e)
            {
                ManageScriptException(e); // always throws
                // This quiets the compiler which wants to see a return value
                // in all codepaths.
                throw;
            }
            catch (Exception e)
            {
                // This cmdlet threw an exception, so
                // wrap it and bubble it up.
                throw ManageInvocationException(e);
            }
        }
Exemplo n.º 19
0
 internal DlrScriptCommandProcessor(ExternalScriptInfo scriptInfo, ExecutionContext context, bool useNewScope, SessionStateInternal sessionState)
     : base(scriptInfo, context, useNewScope, sessionState)
 {
     Init();
 }
Exemplo n.º 20
0
 internal DlrScriptCommandProcessor(ScriptBlock scriptBlock, ExecutionContext context, bool useNewScope, CommandOrigin origin, SessionStateInternal sessionState)
     : base(scriptBlock, context, useNewScope, origin, sessionState)
 {
     Init();
 }
Exemplo n.º 21
0
        /// <summary>
        /// Collect values for UsingExpressions, in the form of a dictionary and an array.
        ///  - The dictionary form is used when the remote server is PSv5 and later version for handling UsingExpression in Invoke-Command/Start-Job
        ///  - The array form is used when the remote server is PSv3 and PSv4 for handling UsingExpression in Invoke-Command.
        /// </summary>
        /// <remarks>
        /// We still keep the array-form using values because we want to avoid any breaking changes when running Invoke-Command
        /// targeting PSv3 or PSv4 remote end -- if UsingExpressions are all in the same scope, then we still pass an array of using
        /// values to the remote end; otherwise, we will handle UsingExpression as if the remote end is PSv2.
        /// </remarks>
        /// <returns>
        /// A tuple of the dictionary-form and the array-form using values.
        /// If the array-form using value is null, then there are UsingExpressions used in different scopes.
        /// </returns>
        private static Tuple <Dictionary <string, object>, object[]> GetUsingValues(Ast body, bool isTrustedInput, ExecutionContext context, Dictionary <string, object> variables, bool filterNonUsingVariables)
        {
            Diagnostics.Assert(context != null || variables != null, "can't retrieve variables with no context and no variables");

            var usingAsts                  = UsingExpressionAstSearcher.FindAllUsingExpressionExceptForWorkflow(body).ToList();
            var usingValueArray            = new object[usingAsts.Count];
            var usingValueMap              = new Dictionary <string, object>(usingAsts.Count);
            HashSet <string> usingVarNames = (variables != null && filterNonUsingVariables) ? new HashSet <string>() : null;

            // Used to check if the PSv3/PSv4 way of handling UsingExpression can continue to be used.
            bool           hasUsingExprInDifferentScope = false;
            ScriptBlockAst sbClosestToPreUsingExpr      = null;

            UsingExpressionAst usingAst         = null;
            Version            oldStrictVersion = null;

            try
            {
                if (context != null)
                {
                    oldStrictVersion = context.EngineSessionState.CurrentScope.StrictModeVersion;
                    context.EngineSessionState.CurrentScope.StrictModeVersion = PSVersionInfo.PSVersion;
                }

                for (int i = 0; i < usingAsts.Count; ++i)
                {
                    usingAst = (UsingExpressionAst)usingAsts[i];
                    object value = null;

                    // This happens only when GetUsingValues gets called outside the ScriptBlockToPowerShellConverter class
                    if (!hasUsingExprInDifferentScope && HasUsingExpressionsInDifferentScopes(usingAst, body, ref sbClosestToPreUsingExpr))
                    {
                        // If there are UsingExpressions in different scopes, the array-form using values will not be useful
                        // even if the remote end is PSv3 or PSv4, because the way we handle using expression in PSv3 and PSv4
                        // doesn't support UsingExpression in different scopes. In this case, we will set the array-form using
                        // value to be null before return.
                        //
                        // Note that this check only affect array-form using value. In PSv5, we change the way to handle UsingExpression
                        // on both client and server sides. The dictionary-form using values is used and UsingExpression in different
                        // scope is supported.
                        hasUsingExprInDifferentScope = true;
                    }

                    if (variables != null)
                    {
                        var variableAst = usingAst.SubExpression as VariableExpressionAst;
                        if (variableAst == null)
                        {
                            throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException),
                                                                           usingAst.Extent, "CantGetUsingExpressionValueWithSpecifiedVariableDictionary", AutomationExceptions.CantGetUsingExpressionValueWithSpecifiedVariableDictionary, usingAst.Extent.Text);
                        }

                        string varName = variableAst.VariablePath.UserPath;
                        if (varName != null && variables.TryGetValue(varName, out value) && usingVarNames != null)
                        {
                            usingVarNames.Add(varName);
                        }
                    }
                    else
                    {
                        value = Compiler.GetExpressionValue(usingAst.SubExpression, isTrustedInput, context);
                    }

                    // Collect UsingExpression value as an array
                    usingValueArray[i] = value;

                    // Collect UsingExpression value as a dictionary
                    string usingAstKey = PsUtils.GetUsingExpressionKey(usingAst);
                    if (!usingValueMap.ContainsKey(usingAstKey))
                    {
                        usingValueMap.Add(usingAstKey, value);
                    }
                }
            }
            catch (RuntimeException rte)
            {
                if (rte.ErrorRecord.FullyQualifiedErrorId.Equals("VariableIsUndefined", StringComparison.Ordinal))
                {
                    throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException),
                                                                   usingAst.Extent, "UsingVariableIsUndefined", AutomationExceptions.UsingVariableIsUndefined, rte.ErrorRecord.TargetObject);
                }
                else if (rte.ErrorRecord.FullyQualifiedErrorId.Equals("CantGetUsingExpressionValueWithSpecifiedVariableDictionary", StringComparison.Ordinal))
                {
                    throw;
                }
            }
            finally
            {
                if (context != null)
                {
                    context.EngineSessionState.CurrentScope.StrictModeVersion = oldStrictVersion;
                }
            }

            if (usingVarNames != null)
            {
                string[] keys = variables.Keys.ToArray();
                foreach (string key in keys)
                {
                    if (!usingVarNames.Contains(key))
                    {
                        variables.Remove(key);
                    }
                }
            }

            if (hasUsingExprInDifferentScope)
            {
                usingValueArray = null;
            }

            return(Tuple.Create(usingValueMap, usingValueArray));
        }
Exemplo n.º 22
0
 /// <summary>
 /// Constructor for HtmlWebResponseObject
 /// </summary>
 /// <param name="response"></param>
 /// <param name="executionContext"></param>
 internal HtmlWebResponseObject(HttpResponseMessage response, ExecutionContext executionContext)
     : this(response, null, executionContext)
 {
 }
Exemplo n.º 23
0
 /// <summary>
 /// Constructor for HtmlWebResponseObject
 /// </summary>
 /// <param name="response"></param>
 /// <param name="executionContext"></param>
 internal HtmlWebResponseObject(HttpResponseMessage response, ExecutionContext executionContext)
     : this(response, null, executionContext)
 { }
Exemplo n.º 24
0
 /// <summary>
 /// Set current engine state for the engine instance corresponding to executionContext
 /// passed in.
 ///
 /// Engine state is stored in ExecutionContext.
 /// </summary>
 /// <param name="executionContext"></param>
 /// <param name="engineState"></param>
 private static void SetEngineState(ExecutionContext executionContext, EngineState engineState)
 {
     executionContext.EngineState = engineState;
 }
Exemplo n.º 25
0
        private Dictionary <string, UpdatableHelpModuleInfo> GetModuleInfo(System.Management.Automation.ExecutionContext context, string pattern, bool loaded, bool noErrors)
        {
            List <PSModuleInfo> modules = context.Modules.GetModules(new string[] { pattern }, false);
            Dictionary <string, UpdatableHelpModuleInfo> dictionary = new Dictionary <string, UpdatableHelpModuleInfo>();

            if (modules.Count != 0)
            {
                base.WriteDebug(StringUtil.Format("Found {0} loaded modules.", modules.Count));
                foreach (PSModuleInfo info in modules)
                {
                    if (InitialSessionState.IsEngineModule(info.Name) && !InitialSessionState.IsNestedEngineModule(info.Name))
                    {
                        base.WriteDebug(StringUtil.Format("Found engine module: {0}, {1}.", info.Name, info.Guid));
                        if (!dictionary.ContainsKey(info.Name))
                        {
                            dictionary.Add(info.Name, new UpdatableHelpModuleInfo(info.Name, info.Guid, Utils.GetApplicationBase(context.ShellID), metadataCache[info.Name]));
                        }
                    }
                    else if (!InitialSessionState.IsNestedEngineModule(info.Name))
                    {
                        if (string.IsNullOrEmpty(info.HelpInfoUri))
                        {
                            if (!noErrors)
                            {
                                this.ProcessException(info.Name, null, new UpdatableHelpSystemException("HelpInfoUriNotFound", StringUtil.Format(HelpDisplayStrings.HelpInfoUriNotFound, new object[0]), ErrorCategory.NotSpecified, new Uri("HelpInfoUri", UriKind.Relative), null));
                            }
                        }
                        else if (!info.HelpInfoUri.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
                        {
                            if (!noErrors)
                            {
                                this.ProcessException(info.Name, null, new UpdatableHelpSystemException("InvalidHelpInfoUriFormat", StringUtil.Format(HelpDisplayStrings.InvalidHelpInfoUriFormat, info.HelpInfoUri), ErrorCategory.NotSpecified, new Uri("HelpInfoUri", UriKind.Relative), null));
                            }
                        }
                        else if (!dictionary.ContainsKey(info.Name))
                        {
                            dictionary.Add(info.Name, new UpdatableHelpModuleInfo(info.Name, info.Guid, info.ModuleBase, info.HelpInfoUri));
                        }
                    }
                }
            }
            WildcardOptions options = WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase;
            IEnumerable <WildcardPattern> patterns = SessionStateUtilities.CreateWildcardsFromStrings(new string[] { pattern }, options);

            if (!loaded)
            {
                Collection <PSObject>     collection  = base.InvokeCommand.InvokeScript("Get-Module -ListAvailable");
                Collection <PSModuleInfo> collection2 = new Collection <PSModuleInfo>();
                if (collection != null)
                {
                    foreach (PSObject obj2 in collection)
                    {
                        try
                        {
                            collection2.Add((PSModuleInfo)LanguagePrimitives.ConvertTo(obj2, typeof(PSModuleInfo), CultureInfo.InvariantCulture));
                        }
                        catch (PSInvalidCastException)
                        {
                        }
                    }
                }
                base.WriteDebug(StringUtil.Format("Found {0} available (Get-Module -ListAvailable) modules.", collection2.Count));
                foreach (PSModuleInfo info2 in collection2)
                {
                    if (SessionStateUtilities.MatchesAnyWildcardPattern(info2.Name, patterns, true))
                    {
                        if (InitialSessionState.IsEngineModule(info2.Name) && !InitialSessionState.IsNestedEngineModule(info2.Name))
                        {
                            base.WriteDebug(StringUtil.Format("Found engine module: {0}, {1}.", info2.Name, info2.Guid));
                            if (!dictionary.ContainsKey(info2.Name))
                            {
                                dictionary.Add(info2.Name, new UpdatableHelpModuleInfo(info2.Name, info2.Guid, Utils.GetApplicationBase(context.ShellID), metadataCache[info2.Name]));
                            }
                        }
                        else if (!InitialSessionState.IsNestedEngineModule(info2.Name))
                        {
                            if (string.IsNullOrEmpty(info2.HelpInfoUri))
                            {
                                if (!noErrors)
                                {
                                    this.ProcessException(info2.Name, null, new UpdatableHelpSystemException("HelpInfoUriNotFound", StringUtil.Format(HelpDisplayStrings.HelpInfoUriNotFound, new object[0]), ErrorCategory.NotSpecified, new Uri("HelpInfoUri", UriKind.Relative), null));
                                }
                            }
                            else if (!info2.HelpInfoUri.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
                            {
                                if (!noErrors)
                                {
                                    this.ProcessException(info2.Name, null, new UpdatableHelpSystemException("InvalidHelpInfoUriFormat", StringUtil.Format(HelpDisplayStrings.InvalidHelpInfoUriFormat, info2.HelpInfoUri), ErrorCategory.NotSpecified, new Uri("HelpInfoUri", UriKind.Relative), null));
                                }
                            }
                            else if (!dictionary.ContainsKey(info2.Name))
                            {
                                dictionary.Add(info2.Name, new UpdatableHelpModuleInfo(info2.Name, info2.Guid, info2.ModuleBase, info2.HelpInfoUri));
                            }
                        }
                    }
                }
            }
            foreach (KeyValuePair <string, string> pair in metadataCache)
            {
                if (SessionStateUtilities.MatchesAnyWildcardPattern(pair.Key, patterns, true))
                {
                    if (!pair.Key.Equals(InitialSessionState.CoreSnapin, StringComparison.OrdinalIgnoreCase))
                    {
                        Collection <PSObject>     collection3 = base.InvokeCommand.InvokeScript(StringUtil.Format("Get-Module {0} -ListAvailable", pair.Key));
                        Collection <PSModuleInfo> collection4 = new Collection <PSModuleInfo>();
                        if (collection3 != null)
                        {
                            foreach (PSObject obj3 in collection3)
                            {
                                try
                                {
                                    collection4.Add((PSModuleInfo)LanguagePrimitives.ConvertTo(obj3, typeof(PSModuleInfo), CultureInfo.InvariantCulture));
                                }
                                catch (PSInvalidCastException)
                                {
                                }
                            }
                        }
                        foreach (PSModuleInfo info3 in collection4)
                        {
                            if (!dictionary.ContainsKey(info3.Name))
                            {
                                base.WriteDebug(StringUtil.Format("Found engine module: {0}, {1}.", info3.Name, info3.Guid));
                                dictionary.Add(pair.Key, new UpdatableHelpModuleInfo(info3.Name, info3.Guid, Utils.GetApplicationBase(context.ShellID), metadataCache[info3.Name]));
                            }
                        }
                    }
                    else if (!dictionary.ContainsKey(pair.Key))
                    {
                        dictionary.Add(pair.Key, new UpdatableHelpModuleInfo(pair.Key, Guid.Empty, Utils.GetApplicationBase(context.ShellID), pair.Value));
                    }
                }
            }
            return(dictionary);
        }
Exemplo n.º 26
0
        internal static List <string> GetDefaultAvailableModuleFiles(bool force, bool preferSystemModulePath, System.Management.Automation.ExecutionContext context)
        {
            Pipeline currentlyRunningPipeline = context.CurrentRunspace.GetCurrentlyRunningPipeline();

            if (!force && (currentlyRunningPipeline != null))
            {
                lock (cachedAvailableModuleFiles)
                {
                    if ((currentlyRunningPipeline.InstanceId == pipelineInstanceIdForModuleFileCache) && (cachedAvailableModuleFiles.Count > 0))
                    {
                        return(cachedAvailableModuleFiles);
                    }
                }
            }
            List <string> availableModuleFiles = new List <string>();
            List <string> modulePaths          = new List <string>();

            foreach (string str in ModuleIntrinsics.GetModulePath(preferSystemModulePath, context))
            {
                if (Directory.Exists(str))
                {
                    GetDefaultAvailableModuleFiles(str, availableModuleFiles, modulePaths);
                }
            }
            if (currentlyRunningPipeline != null)
            {
                lock (cachedAvailableModuleFiles)
                {
                    pipelineInstanceIdForModuleFileCache = currentlyRunningPipeline.InstanceId;
                    cachedAvailableModuleFiles           = availableModuleFiles;
                }
            }
            return(availableModuleFiles);
        }
Exemplo n.º 27
0
 internal CommandInvocationIntrinsics(ExecutionContext executionContext, PipelineCommandRuntime commandRuntime)
 {
     this.executionContext = executionContext;
     this.commandRuntime   = commandRuntime;
 }
Exemplo n.º 28
0
 /// <summary>
 /// Initializes a new instance of the DscResourceInfo class
 /// </summary>
 /// <param name="name">Name of the DscResource.</param>
 /// <param name="friendlyName">FriendlyName of the DscResource.</param>
 /// <param name="path">Path of the DscResource.</param>
 /// <param name="parentPath">ParentPath of the DscResource.</param>
 /// <param name="context">The execution context for the DscResource.</param>
 internal DscResourceInfo(string name, string friendlyName, string path, string parentPath, ExecutionContext context)
 {
     this.Name         = name;
     this.FriendlyName = friendlyName;
     this.Path         = path;
     this.ParentPath   = parentPath;
     this.Properties   = new ReadOnlyCollection <DscResourcePropertyInfo>(new List <DscResourcePropertyInfo>());
 }
Exemplo n.º 29
0
        /// <summary>
        /// NeedToLogPipelineExecutionDetailEvent: check whether logging pipeline execution detail event is necessary.
        ///
        /// Whether to log command lifecycle event is controled by PSSnapin set up.
        ///
        /// Should we use session variable "LogPipelineExecutionEvent" to control this also?
        ///
        /// Currently we return true always since pipeline processor already check for whether to log
        /// logic from PSSnapin already. This may need to be changed.
        /// </summary>
        /// <param name="logProvider"></param>
        /// <param name="executionContext"></param>
        /// <returns></returns>
        private static bool NeedToLogPipelineExecutionDetailEvent(LogProvider logProvider, ExecutionContext executionContext)
        {
            if (!logProvider.UseLoggingVariables())
            {
                return(true);
            }

            return(true);
            // return LanguagePrimitives.IsTrue(executionContext.GetVariable("LogPipelineExecutionDetailEvent", false));
        }
Exemplo n.º 30
0
        /// <summary>
        /// Constructor for InvocationInfo object
        /// </summary>
        /// <param name="commandInfo">
        /// The command information the invocation info represents.
        /// </param>
        /// <param name="scriptPosition">
        /// The position representing the invocation, or the position representing the error.
        /// </param>
        /// <param name="context">
        /// The context in which the InvocationInfo is being created.
        /// </param>
        internal InvocationInfo(CommandInfo commandInfo, IScriptExtent scriptPosition, ExecutionContext context)
        {
            MyCommand       = commandInfo;
            CommandOrigin   = CommandOrigin.Internal;
            _scriptPosition = scriptPosition;

            ExecutionContext contextToUse = null;

            if ((commandInfo != null) && (commandInfo.Context != null))
            {
                contextToUse = commandInfo.Context;
            }
            else if (context != null)
            {
                contextToUse = context;
            }

            // Populate the history ID of this command
            if (contextToUse != null)
            {
                Runspaces.LocalRunspace localRunspace = contextToUse.CurrentRunspace as Runspaces.LocalRunspace;
                if (localRunspace != null && localRunspace.History != null)
                {
                    HistoryId = localRunspace.History.GetNextHistoryId();
                }
            }
        }
Exemplo n.º 31
0
 /// <summary>
 /// Generate LogContext structure based on executionContext and invocationInfo passed in.
 ///
 /// LogContext structure is used in log provider interface.
 /// </summary>
 /// <param name="executionContext"></param>
 /// <param name="invocationInfo"></param>
 /// <returns></returns>
 internal static LogContext GetLogContext(ExecutionContext executionContext, InvocationInfo invocationInfo)
 {
     return(GetLogContext(executionContext, invocationInfo, Severity.Informational));
 }
Exemplo n.º 32
0
        internal static PowerShell Convert(ScriptBlockAst body,
                                           ReadOnlyCollection <ParameterAst> functionParameters,
                                           bool isTrustedInput,
                                           ExecutionContext context,
                                           Dictionary <string, object> variables,
                                           bool filterNonUsingVariables,
                                           bool?createLocalScope,
                                           object[] args)
        {
            ExecutionContext.CheckStackDepth();

            if (args == null)
            {
                args = Utils.EmptyArray <object>();
            }

            // Perform validations on the ScriptBlock.  GetSimplePipeline can allow for more than one
            // pipeline if the first parameter is true, but Invoke-Command doesn't yet support multiple
            // pipelines in a PowerShell (it just grabs the last command directly.)  The rest of this
            // code properly supports multiple pipelines, so it should just work to change the false to true
            // if/when Invoke-Command can support multiple pipelines.
            string errorId;
            string errorMsg;

            body.GetSimplePipeline(true, out errorId, out errorMsg);
            if (errorId != null)
            {
                throw new ScriptBlockToPowerShellNotSupportedException(errorId, null, errorMsg);
            }

            var checker = new ScriptBlockToPowerShellChecker {
                ScriptBeingConverted = body
            };

            if (functionParameters != null)
            {
                foreach (var parameter in functionParameters)
                {
                    parameter.InternalVisit(checker);
                }
            }

            body.InternalVisit(checker);

            // When the context is null (or they haven't supplied any variables), throw, but only if we really need the
            // context (basically, if we have some variable reference to resolve).
            if (context == null && (checker.HasUsingExpr || checker.UsesParameter) && (variables == null))
            {
                throw new PSInvalidOperationException(AutomationExceptions.CantConvertScriptBlockWithNoContext);
            }

            try
            {
                var converter = new ScriptBlockToPowerShellConverter {
                    _context = context, _createLocalScope = createLocalScope
                };

                if (checker.HasUsingExpr)
                {
                    converter._usingValueMap = GetUsingValues(body, isTrustedInput, context, variables, filterNonUsingVariables).Item1;
                }

                if (checker.UsesParameter)
                {
                    // If any parameters are used, we create a new scope and bind the parameters.

                    var newScope = context.EngineSessionState.NewScope(false);
                    context.EngineSessionState.CurrentScope             = newScope;
                    context.EngineSessionState.CurrentScope.ScopeOrigin = CommandOrigin.Internal;

                    var locals =
                        MutableTuple.MakeTuple(Compiler.DottedLocalsTupleType, Compiler.DottedLocalsNameIndexMap);

                    // Get the parameter metadata for the script block.
                    // If 'functionParameters' is not null, then the ScriptBlockAst is actually the body of a FunctionDefinitionAst, and it doesn't have a ParamBlock.
                    // If 'functionParameters' is null, then the ScriptBlockAst may have parameters defined in its ParamBlock.
                    bool usesCmdletBinding = false;
                    var  parameters        = functionParameters != null
                                         ? Compiler.GetParameterMetaData(functionParameters, true, ref usesCmdletBinding)
                                         : ((IParameterMetadataProvider)body).GetParameterMetadata(true, ref usesCmdletBinding);

                    object[] remainingArgs = ScriptBlock.BindArgumentsForScriptblockInvoke(
                        (RuntimeDefinedParameter[])parameters.Data, args, context, false, null, locals);
                    locals.SetAutomaticVariable(AutomaticVariable.Args, remainingArgs, context);
                    newScope.LocalsTuple = locals;
                }

                foreach (var pipeline in body.EndBlock.Statements.OfType <PipelineAst>())
                {
                    converter._powershell.AddStatement();
                    converter.ConvertPipeline(pipeline, isTrustedInput);
                }

                return(converter._powershell);
            }
            finally
            {
                if (checker.UsesParameter)
                {
                    context.EngineSessionState.RemoveScope(context.EngineSessionState.CurrentScope);
                }
            }
        }
Exemplo n.º 33
0
 internal static IEnumerable <CommandInfo> GetMatchingCommands(string pattern, System.Management.Automation.ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false)
 {
     return(new _GetMatchingCommands_d__a(-2)
     {
         __3__pattern = pattern, __3__context = context, __3__commandOrigin = commandOrigin, __3__rediscoverImportedModules = rediscoverImportedModules
     });
 }
Exemplo n.º 34
0
        /// <summary>
        /// Generate LogContext structure based on executionContext and invocationInfo passed in.
        ///
        /// LogContext structure is used in log provider interface.
        /// </summary>
        /// <param name="executionContext"></param>
        /// <param name="invocationInfo"></param>
        /// <param name="severity"></param>
        /// <returns></returns>
        private static LogContext GetLogContext(ExecutionContext executionContext, InvocationInfo invocationInfo, Severity severity)
        {
            if (executionContext == null)
            {
                return(null);
            }

            LogContext logContext = new LogContext();

            string shellId = executionContext.ShellID;

            logContext.ExecutionContext = executionContext;
            logContext.ShellId          = shellId;
            logContext.Severity         = severity.ToString();

            if (executionContext.EngineHostInterface != null)
            {
                logContext.HostName    = executionContext.EngineHostInterface.Name;
                logContext.HostVersion = executionContext.EngineHostInterface.Version.ToString();
                logContext.HostId      = (string)executionContext.EngineHostInterface.InstanceId.ToString();
            }

            logContext.HostApplication = string.Join(" ", Environment.GetCommandLineArgs());

            if (executionContext.CurrentRunspace != null)
            {
                logContext.EngineVersion = executionContext.CurrentRunspace.Version.ToString();
                logContext.RunspaceId    = executionContext.CurrentRunspace.InstanceId.ToString();

                Pipeline currentPipeline = ((RunspaceBase)executionContext.CurrentRunspace).GetCurrentlyRunningPipeline();
                if (currentPipeline != null)
                {
                    logContext.PipelineId = currentPipeline.InstanceId.ToString(CultureInfo.CurrentCulture);
                }
            }

            logContext.SequenceNumber = NextSequenceNumber;

            try
            {
                if (executionContext.LogContextCache.User == null)
                {
                    logContext.User = Environment.UserDomainName + "\\" + Environment.UserName;
                    executionContext.LogContextCache.User = logContext.User;
                }
                else
                {
                    logContext.User = executionContext.LogContextCache.User;
                }
            }
            catch (InvalidOperationException)
            {
                logContext.User = Logging.UnknownUserName;
            }

            System.Management.Automation.Remoting.PSSenderInfo psSenderInfo =
                executionContext.SessionState.PSVariable.GetValue("PSSenderInfo") as System.Management.Automation.Remoting.PSSenderInfo;
            if (psSenderInfo != null)
            {
                logContext.ConnectedUser = psSenderInfo.UserInfo.Identity.Name;
            }

            logContext.Time = DateTime.Now.ToString(CultureInfo.CurrentCulture);

            if (invocationInfo == null)
            {
                return(logContext);
            }

            logContext.ScriptName  = invocationInfo.ScriptName;
            logContext.CommandLine = invocationInfo.Line;

            if (invocationInfo.MyCommand != null)
            {
                logContext.CommandName = invocationInfo.MyCommand.Name;
                logContext.CommandType = invocationInfo.MyCommand.CommandType.ToString();

                switch (invocationInfo.MyCommand.CommandType)
                {
                case CommandTypes.Application:
                    logContext.CommandPath = ((ApplicationInfo)invocationInfo.MyCommand).Path;
                    break;

                case CommandTypes.ExternalScript:
                    logContext.CommandPath = ((ExternalScriptInfo)invocationInfo.MyCommand).Path;
                    break;
                }
            }

            return(logContext);
        }