예제 #1
0
        internal void SetPSBoundParametersVariable(ExecutionContext context)
        {
            PSObject psObject = PSObject.AsPSObject((object)this.dictionary);

            psObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("BoundPositionally", (object)this.boundPositionally));
            context.SetVariable("PSBoundParameters", (object)psObject);
        }
예제 #2
0
        private void SetErrorVariables(
            Token statementToken,
            RuntimeException rte,
            ExecutionContext context,
            Pipe outputPipe)
        {
            string    str       = (string)null;
            Exception exception = (Exception)rte;

            for (int index = 0; exception != null && index++ < 10; exception = exception.InnerException)
            {
                if (!string.IsNullOrEmpty(exception.StackTrace))
                {
                    str = exception.StackTrace;
                }
            }
            context.SetVariable("global:StackTrace", (object)str);
            if (rte.ErrorRecord.InvocationInfo == null)
            {
                rte.ErrorRecord.SetInvocationInfo(new InvocationInfo((CommandInfo)null, statementToken, context));
            }
            ErrorRecord errorRecord = new ErrorRecord(rte.ErrorRecord, (Exception)rte);

            if (rte is PipelineStoppedException)
            {
                return;
            }
            outputPipe?.UpdateScriptCmdletVariable(ScriptCmdletVariable.Error, (object)errorRecord);
            context.AppendDollarError((object)errorRecord);
        }
예제 #3
0
        internal static void SetErrorVariables(IScriptExtent extent, RuntimeException rte, ExecutionContext context, Pipe outputPipe)
        {
            string    newValue       = null;
            Exception innerException = rte;
            int       num            = 0;

            while ((innerException != null) && (num++ < 10))
            {
                if (!string.IsNullOrEmpty(innerException.StackTrace))
                {
                    newValue = innerException.StackTrace;
                }
                innerException = innerException.InnerException;
            }
            context.SetVariable(SpecialVariables.StackTraceVarPath, newValue);
            InterpreterError.UpdateExceptionErrorRecordPosition(rte, extent);
            ErrorRecord record = rte.ErrorRecord.WrapException(rte);

            if (!(rte is PipelineStoppedException))
            {
                if (outputPipe != null)
                {
                    outputPipe.AppendVariableList(VariableStreamKind.Error, record);
                }
                context.AppendDollarError(record);
            }
        }
예제 #4
0
        internal static bool ConditionSatisfiedRegex(bool caseSensitive, object condition, IScriptExtent errorPosition, string str, ExecutionContext context)
        {
            string       str2;
            bool         success;
            RegexOptions options = caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;

            try
            {
                Match match;
                Regex regex = condition as Regex;
                if ((regex != null) && (((regex.Options & RegexOptions.IgnoreCase) != RegexOptions.None) != caseSensitive))
                {
                    match = regex.Match(str);
                }
                else
                {
                    str2  = PSObject.ToStringParser(context, condition);
                    match = Regex.Match(str, str2, options);
                    if (match.Success && (match.Groups.Count > 0))
                    {
                        regex = new Regex(str2, options);
                    }
                }
                if (match.Success)
                {
                    GroupCollection groups = match.Groups;
                    if (groups.Count > 0)
                    {
                        Hashtable newValue = new Hashtable(StringComparer.CurrentCultureIgnoreCase);
                        foreach (string str3 in regex.GetGroupNames())
                        {
                            Group group = groups[str3];
                            if (group.Success)
                            {
                                int num;
                                if (int.TryParse(str3, out num))
                                {
                                    newValue.Add(num, group.ToString());
                                }
                                else
                                {
                                    newValue.Add(str3, group.ToString());
                                }
                            }
                        }
                        context.SetVariable(SpecialVariables.MatchesVarPath, newValue);
                    }
                }
                success = match.Success;
            }
            catch (ArgumentException exception)
            {
                str2 = PSObject.ToStringParser(context, condition);
                throw InterpreterError.NewInterpreterExceptionWithInnerException(str2, typeof(RuntimeException), errorPosition, "InvalidRegularExpression", ParserStrings.InvalidRegularExpression, exception, new object[] { str2 });
            }
            return(success);
        }
예제 #5
0
        public PSModuleInfo(ScriptBlock scriptBlock)
        {
            this._name                         = string.Empty;
            this._path                         = string.Empty;
            this._description                  = string.Empty;
            this._version                      = new System.Version(0, 0);
            this._detectedFunctionExports      = new List <string>();
            this._detectedWorkflowExports      = new List <string>();
            this._detectedCmdletExports        = new List <string>();
            this._compiledExports              = new List <CmdletInfo>();
            this._fileList                     = new List <string>();
            this._moduleList                   = new Collection <object>();
            this._nestedModules                = new List <PSModuleInfo>();
            this._scripts                      = new List <string>();
            this._requiredAssemblies           = new Collection <string>();
            this._requiredModules              = new List <PSModuleInfo>();
            this._requiredModulesSpecification = new List <ModuleSpecification>();
            this._detectedAliasExports         = new Dictionary <string, string>();
            this._exportedFormatFiles          = new ReadOnlyCollection <string>(new List <string>());
            this._exportedTypeFiles            = new ReadOnlyCollection <string>(new List <string>());
            if (scriptBlock == null)
            {
                throw PSTraceSource.NewArgumentException("scriptBlock");
            }
            ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();

            if (executionContextFromTLS == null)
            {
                throw new InvalidOperationException("PSModuleInfo");
            }
            SetDefaultDynamicNameAndPath(this);
            this._sessionState = new System.Management.Automation.SessionState(executionContextFromTLS, true, true);
            this._sessionState.Internal.Module = this;
            SessionStateInternal engineSessionState = executionContextFromTLS.EngineSessionState;

            try
            {
                executionContextFromTLS.EngineSessionState = this._sessionState.Internal;
                executionContextFromTLS.SetVariable(SpecialVariables.PSScriptRootVarPath, this._path);
                scriptBlock = scriptBlock.Clone(true);
                scriptBlock.SessionState = this._sessionState;
                Pipe outputPipe = new Pipe {
                    NullPipe = true
                };
                scriptBlock.InvokeWithPipe(false, ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, AutomationNull.Value, AutomationNull.Value, AutomationNull.Value, outputPipe, null, new object[0]);
            }
            finally
            {
                executionContextFromTLS.EngineSessionState = engineSessionState;
            }
        }
예제 #6
0
        /// <summary>
        /// Get a Hashtable object out of a PowerShell data file (.psd1)
        /// </summary>
        /// <param name="parameterName">
        /// Name of the parameter that takes the specified .psd1 file as a value
        /// </param>
        /// <param name="psDataFilePath">
        /// Path to the powershell data file
        /// </param>
        /// <param name="context">
        /// ExecutionContext to use
        /// </param>
        /// <param name="allowedCommands">
        /// Set of command names that are allowed to use in the .psd1 file
        /// </param>
        /// <param name="allowedVariables">
        /// Set of variable names that are allowed to use in the .psd1 file
        /// </param>
        /// <param name="allowEnvironmentVariables">
        /// If true, allow to use environment variables in the .psd1 file
        /// </param>
        /// <param name="skipPathValidation">
        /// If true, caller guarantees the path is valid
        /// </param>
        /// <returns></returns>
        internal static Hashtable EvaluatePowerShellDataFile(
            string parameterName,
            string psDataFilePath,
            ExecutionContext context,
            IEnumerable <string> allowedCommands,
            IEnumerable <string> allowedVariables,
            bool allowEnvironmentVariables,
            bool skipPathValidation)
        {
            if (!skipPathValidation && string.IsNullOrEmpty(parameterName))
            {
                throw PSTraceSource.NewArgumentNullException("parameterName");
            }

            if (string.IsNullOrEmpty(psDataFilePath))
            {
                throw PSTraceSource.NewArgumentNullException("psDataFilePath");
            }

            if (context == null)
            {
                throw PSTraceSource.NewArgumentNullException("context");
            }

            string resolvedPath;

            if (skipPathValidation)
            {
                resolvedPath = psDataFilePath;
            }
            else
            {
                #region "ValidatePowerShellDataFilePath"

                bool isPathValid = true;

                // File extension needs to be .psd1
                string pathExt = Path.GetExtension(psDataFilePath);
                if (string.IsNullOrEmpty(pathExt) ||
                    !StringLiterals.PowerShellDataFileExtension.Equals(pathExt, StringComparison.OrdinalIgnoreCase))
                {
                    isPathValid = false;
                }

                ProviderInfo provider;
                var          resolvedPaths = context.SessionState.Path.GetResolvedProviderPathFromPSPath(psDataFilePath, out provider);

                // ConfigPath should be resolved as FileSystem provider
                if (provider == null || !Microsoft.PowerShell.Commands.FileSystemProvider.ProviderName.Equals(provider.Name, StringComparison.OrdinalIgnoreCase))
                {
                    isPathValid = false;
                }

                // ConfigPath should be resolved to a single path
                if (resolvedPaths.Count != 1)
                {
                    isPathValid = false;
                }

                if (!isPathValid)
                {
                    throw PSTraceSource.NewArgumentException(
                              parameterName,
                              ParserStrings.CannotResolvePowerShellDataFilePath,
                              psDataFilePath);
                }

                resolvedPath = resolvedPaths[0];

                #endregion "ValidatePowerShellDataFilePath"
            }

            #region "LoadAndEvaluatePowerShellDataFile"

            object evaluationResult;
            try
            {
                // Create the scriptInfo for the .psd1 file
                string      dataFileName       = Path.GetFileName(resolvedPath);
                var         dataFileScriptInfo = new ExternalScriptInfo(dataFileName, resolvedPath, context);
                ScriptBlock scriptBlock        = dataFileScriptInfo.ScriptBlock;

                // Validate the scriptblock
                scriptBlock.CheckRestrictedLanguage(allowedCommands, allowedVariables, allowEnvironmentVariables);

                // Evaluate the scriptblock
                object oldPsScriptRoot = context.GetVariableValue(SpecialVariables.PSScriptRootVarPath);
                try
                {
                    // Set the $PSScriptRoot before the evaluation
                    context.SetVariable(SpecialVariables.PSScriptRootVarPath, Path.GetDirectoryName(resolvedPath));
                    evaluationResult = PSObject.Base(scriptBlock.InvokeReturnAsIs());
                }
                finally
                {
                    context.SetVariable(SpecialVariables.PSScriptRootVarPath, oldPsScriptRoot);
                }
            }
            catch (RuntimeException ex)
            {
                throw PSTraceSource.NewInvalidOperationException(
                          ex,
                          ParserStrings.CannotLoadPowerShellDataFile,
                          psDataFilePath,
                          ex.Message);
            }

            var retResult = evaluationResult as Hashtable;
            if (retResult == null)
            {
                throw PSTraceSource.NewInvalidOperationException(
                          ParserStrings.InvalidPowerShellDataFile,
                          psDataFilePath);
            }

            #endregion "LoadAndEvaluatePowerShellDataFile"

            return(retResult);
        }
예제 #7
0
 internal void SetPSBoundParametersVariable(ExecutionContext context)
 {
     context.SetVariable(SpecialVariables.PSBoundParametersVarPath, this._dictionary);
 }
예제 #8
0
 /// <summary>
 /// In the cleanup phase, the command's "EndProcessing" method will be called to do own cleanup
 /// </summary>
 public override void EndProcessing()
 {
     Command.DoEndProcessing();
     ExecutionContext.SetVariable("global:?", true); // only false if we got an exception
 }