예제 #1
0
        internal static object InvokeAdaptedSetMember(object obj, string methodName, object[] args, object valueToSet)
        {
            TypeTable        typeTable;
            ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();
            object           obj1 = obj;

            if (executionContextFromTLS != null)
            {
                typeTable = executionContextFromTLS.TypeTable;
            }
            else
            {
                typeTable = null;
            }
            PSObject.AdapterSet     mappedAdapter           = PSObject.GetMappedAdapter(obj1, typeTable);
            PSParameterizedProperty pSParameterizedProperty = mappedAdapter.OriginalAdapter.BaseGetMember <PSParameterizedProperty>(obj, methodName);

            if (pSParameterizedProperty == null && mappedAdapter.DotNetAdapter != null)
            {
                pSParameterizedProperty = mappedAdapter.DotNetAdapter.BaseGetMember <PSParameterizedProperty>(obj, methodName);
            }
            if (pSParameterizedProperty == null)
            {
                object[] typeFullName = new object[2];
                typeFullName[0] = ParserOps.GetTypeFullName(obj);
                typeFullName[1] = methodName;
                throw InterpreterError.NewInterpreterException(methodName, typeof(RuntimeException), null, "MethodNotFound", ParserStrings.MethodNotFound, typeFullName);
            }
            else
            {
                pSParameterizedProperty.InvokeSet(valueToSet, args);
                return(valueToSet);
            }
        }
예제 #2
0
        internal static bool TryGetInstanceMethod(object value, string memberName, out PSMethodInfo methodInfo)
        {
            PSMemberInfoInternalCollection <PSMemberInfo> pSMemberInfos = null;
            PSMemberInfo item;

            if (PSObject.HasInstanceMembers(value, out pSMemberInfos))
            {
                item = pSMemberInfos[memberName];
            }
            else
            {
                item = null;
            }
            PSMemberInfo pSMemberInfo = item;

            methodInfo = pSMemberInfo as PSMethodInfo;
            if (pSMemberInfo != null)
            {
                if (methodInfo != null)
                {
                    return(true);
                }
                else
                {
                    object[] typeFullName = new object[2];
                    typeFullName[0] = ParserOps.GetTypeFullName(value);
                    typeFullName[1] = memberName;
                    throw InterpreterError.NewInterpreterException(memberName, typeof(RuntimeException), null, "MethodNotFound", ParserStrings.MethodNotFound, typeFullName);
                }
            }
            else
            {
                return(false);
            }
        }
예제 #3
0
        /// <summary>
        /// Construct the expression from a single string.
        /// </summary>
        /// <param name="expression">
        /// The specified flag attribute expression string.
        /// </param>
        public FlagsExpression(string expression)
        {
            if (!typeof(T).IsEnum)
            {
                throw InterpreterError.NewInterpreterException(expression, typeof(RuntimeException),
                                                               null, "InvalidGenericType", EnumExpressionEvaluatorStrings.InvalidGenericType);
            }

            _underType = Enum.GetUnderlyingType(typeof(T));

            if (string.IsNullOrWhiteSpace(expression))
            {
                throw InterpreterError.NewInterpreterException(expression, typeof(RuntimeException),
                                                               null, "EmptyInputString", EnumExpressionEvaluatorStrings.EmptyInputString);
            }

            List <Token> tokenList = TokenizeInput(expression);

            // Append an OR at the end of the list for construction
            tokenList.Add(new Token(TokenKind.Or));

            CheckSyntaxError(tokenList);

            Root = ConstructExpressionTree(tokenList);
        }
예제 #4
0
        private List <object> GetUsingVariableValues(List <VariableExpressionAst> paramUsingVars)
        {
            List <object>         list = new List <object>(paramUsingVars.Count);
            VariableExpressionAst ast  = null;
            Version strictModeVersion  = base.Context.EngineSessionState.CurrentScope.StrictModeVersion;

            try
            {
                base.Context.EngineSessionState.CurrentScope.StrictModeVersion = PSVersionInfo.PSVersion;
                foreach (VariableExpressionAst ast2 in paramUsingVars)
                {
                    ast = ast2;
                    object item = Compiler.GetExpressionValue(ast2, base.Context, (System.Collections.IList)null);
                    list.Add(item);
                }
                return(list);
            }
            catch (RuntimeException exception)
            {
                if (exception.ErrorRecord.FullyQualifiedErrorId.Equals("VariableIsUndefined", StringComparison.Ordinal))
                {
                    throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), ast.Extent, "UsingVariableIsUndefined", AutomationExceptions.UsingVariableIsUndefined, new object[] { exception.ErrorRecord.TargetObject });
                }
            }
            finally
            {
                base.Context.EngineSessionState.CurrentScope.StrictModeVersion = strictModeVersion;
            }
            return(list);
        }
예제 #5
0
        /// <summary>
        /// Checks syntax errors on input expression,
        /// as well as performing disambiguation for identifiers.
        /// </summary>
        /// <param name="tokenList">
        /// A list of tokenized input.
        /// </param>
        private static void CheckSyntaxError(List <Token> tokenList)
        {
            // Initialize, assuming preceded by OR
            TokenKind previous = TokenKind.Or;

            for (int i = 0; i < tokenList.Count; i++)
            {
                Token token = tokenList[i];
                // Not allowed: ... AND/OR AND/OR ...
                // Allowed: ... AND/OR NOT/ID ...
                if (previous == TokenKind.Or || previous == TokenKind.And)
                {
                    if ((token.Kind == TokenKind.Or) || (token.Kind == TokenKind.And))
                    {
                        throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException),
                                                                       null, "SyntaxErrorUnexpectedBinaryOperator", EnumExpressionEvaluatorStrings.SyntaxErrorUnexpectedBinaryOperator);
                    }
                }
                // Not allowed: ... NOT AND/OR/NOT ...
                // Allowed: ... NOT ID ...
                else if (previous == TokenKind.Not)
                {
                    if (token.Kind != TokenKind.Identifier)
                    {
                        throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException),
                                                                       null, "SyntaxErrorIdentifierExpected", EnumExpressionEvaluatorStrings.SyntaxErrorIdentifierExpected);
                    }
                }
                // Not allowed: ... ID NOT/ID ...
                // Allowed: ... ID AND/OR ...
                else if (previous == TokenKind.Identifier)
                {
                    if ((token.Kind == TokenKind.Identifier) || (token.Kind == TokenKind.Not))
                    {
                        throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException),
                                                                       null, "SyntaxErrorBinaryOperatorExpected", EnumExpressionEvaluatorStrings.SyntaxErrorBinaryOperatorExpected);
                    }
                }

                if (token.Kind == TokenKind.Identifier)
                {
                    string text = token.Text;
                    token.Text = EnumMinimumDisambiguation.EnumDisambiguate(text, typeof(T));
                }

                previous = token.Kind;
            }
        }
예제 #6
0
        private Type resolveType()
        {
            Exception exception = (Exception)null;
            Type      type      = LanguagePrimitives.ConvertStringToType(this._typeName.TokenText, out exception);

            if (type != null)
            {
                this._type = type;
                this._isSwitchParameter = this._type.Equals(typeof(SwitchParameter));
                return(this._type);
            }
            if (exception != null)
            {
                throw InterpreterError.NewInterpreterExceptionWithInnerException((object)this._typeName.TokenText, typeof(RuntimeException), this._typeName, "TypeNotFoundWithMessage", exception, (object)this._typeName.TokenText, (object)exception.Message);
            }
            throw InterpreterError.NewInterpreterException((object)this._typeName.TokenText, typeof(RuntimeException), this._typeName, "TypeNotFound", (object)this._typeName.TokenText);
        }
예제 #7
0
        internal static object SetAdaptedValue(object obj, string member, object value)
        {
            object obj2;

            try
            {
                ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();
                PSMemberInfo     memberInfo = null;
                if ((executionContextFromTLS != null) && (executionContextFromTLS.TypeTable != null))
                {
                    ConsolidatedString typeNames = PSObject.GetTypeNames(obj);
                    memberInfo = executionContextFromTLS.TypeTable.GetMembers <PSMemberInfo>(typeNames)[member];
                    if (memberInfo != null)
                    {
                        memberInfo = PSGetMemberBinder.CloneMemberInfo(memberInfo, obj);
                    }
                }
                PSObject.AdapterSet mappedAdapter = PSObject.GetMappedAdapter(obj, (executionContextFromTLS != null) ? executionContextFromTLS.TypeTable : null);
                if (memberInfo == null)
                {
                    memberInfo = mappedAdapter.OriginalAdapter.BaseGetMember <PSMemberInfo>(obj, member);
                }
                if ((memberInfo == null) && (mappedAdapter.DotNetAdapter != null))
                {
                    memberInfo = mappedAdapter.DotNetAdapter.BaseGetMember <PSMemberInfo>(obj, member);
                }
                if (memberInfo == null)
                {
                    throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "PropertyAssignmentException", ParserStrings.PropertyNotFound, new object[] { member });
                }
                memberInfo.Value = value;
                obj2             = value;
            }
            catch (SetValueException)
            {
                throw;
            }
            catch (Exception exception)
            {
                ExceptionHandlingOps.ConvertToMethodInvocationException(exception, typeof(SetValueInvocationException), member, 0, null);
                throw;
            }
            return(obj2);
        }
예제 #8
0
        /// <summary>
        /// Construct the tree from an object collection when arguments are comma separated.
        /// If valid, all elements are OR separated.
        /// </summary>
        /// <param name="expression">
        /// The array of specified flag attribute subexpression strings.
        /// </param>
        public FlagsExpression(object[] expression)
        {
            if (!typeof(T).IsEnum)
            {
                throw InterpreterError.NewInterpreterException(expression, typeof(RuntimeException),
                                                               null, "InvalidGenericType", EnumExpressionEvaluatorStrings.InvalidGenericType);
            }

            _underType = Enum.GetUnderlyingType(typeof(T));

            if (expression == null)
            {
                throw InterpreterError.NewInterpreterException(null, typeof(ArgumentNullException),
                                                               null, "EmptyInputString", EnumExpressionEvaluatorStrings.EmptyInputString);
            }

            foreach (string inputClause in expression)
            {
                if (string.IsNullOrWhiteSpace(inputClause))
                {
                    throw InterpreterError.NewInterpreterException(expression, typeof(RuntimeException),
                                                                   null, "EmptyInputString", EnumExpressionEvaluatorStrings.EmptyInputString);
                }
            }

            List <Token> tokenList = new List <Token>();

            foreach (string orClause in expression)
            {
                tokenList.AddRange(TokenizeInput(orClause));
                tokenList.Add(new Token(TokenKind.Or));
            }
            // Unnecessary OR at the end not removed for tree construction

            Debug.Assert(tokenList.Count > 0, "Input must not all be white characters.");

            CheckSyntaxError(tokenList);

            Root = ConstructExpressionTree(tokenList);
        }
예제 #9
0
        /// <summary>
        /// </summary>
        protected override void ProcessRecord()
        {
            ProviderInfo        provider = null;
            Collection <string> filePaths;

            try
            {
                if (this.Context.EngineSessionState.IsProviderLoaded(Context.ProviderNames.FileSystem))
                {
                    filePaths = SessionState.Path.GetResolvedProviderPathFromPSPath(_path, out provider);
                }
                else
                {
                    filePaths = new Collection <string>();
                    filePaths.Add(_path);
                }
            }
            catch (ItemNotFoundException)
            {
                string message            = StringUtil.Format(RemotingErrorIdStrings.PSSessionConfigurationFileNotFound, _path);
                FileNotFoundException fnf = new FileNotFoundException(message);
                ErrorRecord           er  = new ErrorRecord(fnf, "PSSessionConfigurationFileNotFound",
                                                            ErrorCategory.ResourceUnavailable, _path);
                WriteError(er);
                return;
            }

            // Make sure that the path is in the file system - that's all we can handle currently...
            if (!provider.NameEquals(this.Context.ProviderNames.FileSystem))
            {
                // "The current provider ({0}) cannot open a file"
                throw InterpreterError.NewInterpreterException(_path, typeof(RuntimeException),
                                                               null, "FileOpenError", ParserStrings.FileOpenError, provider.FullName);
            }

            // Make sure at least one file was found...
            if (filePaths == null || filePaths.Count < 1)
            {
                string message            = StringUtil.Format(RemotingErrorIdStrings.PSSessionConfigurationFileNotFound, _path);
                FileNotFoundException fnf = new FileNotFoundException(message);
                ErrorRecord           er  = new ErrorRecord(fnf, "PSSessionConfigurationFileNotFound",
                                                            ErrorCategory.ResourceUnavailable, _path);
                WriteError(er);
                return;
            }

            if (filePaths.Count > 1)
            {
                // "The path resolved to more than one file; can only process one file at a time."
                throw InterpreterError.NewInterpreterException(filePaths, typeof(RuntimeException),
                                                               null, "AmbiguousPath", ParserStrings.AmbiguousPath);
            }

            string             filePath   = filePaths[0];
            ExternalScriptInfo scriptInfo = null;
            string             ext        = System.IO.Path.GetExtension(filePath);

            if (ext.Equals(StringLiterals.PowerShellDISCFileExtension, StringComparison.OrdinalIgnoreCase))
            {
                // Create a script info for loading the file...
                string scriptName;
                scriptInfo = DISCUtils.GetScriptInfoForFile(this.Context, filePath, out scriptName);

                Hashtable configTable = null;

                try
                {
                    configTable = DISCUtils.LoadConfigFile(this.Context, scriptInfo);
                }
                catch (RuntimeException e)
                {
                    WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCErrorParsingConfigFile, filePath, e.Message));
                    WriteObject(false);
                    return;
                }

                if (configTable == null)
                {
                    WriteObject(false);
                    return;
                }

                DISCUtils.ExecutionPolicyType = typeof(ExecutionPolicy);
                WriteObject(DISCUtils.VerifyConfigTable(configTable, this, filePath));
            }
            else
            {
                string message = StringUtil.Format(RemotingErrorIdStrings.InvalidPSSessionConfigurationFilePath, filePath);
                InvalidOperationException ioe = new InvalidOperationException(message);
                ErrorRecord er = new ErrorRecord(ioe, "InvalidPSSessionConfigurationFilePath",
                                                 ErrorCategory.InvalidArgument, _path);
                ThrowTerminatingError(er);
            }
        }
예제 #10
0
        CreateCommandProcessor
        (
            ExecutionContext executionContext,
            CommandFactory commandFactory,
            bool addToHistory,
            CommandOrigin origin
        )
        {
            Dbg.Assert(executionContext != null, "Caller should verify the parameters");
            Dbg.Assert(commandFactory != null, "Caller should verify the parameters");


            CommandProcessorBase commandProcessorBase;

            if (IsScript)
            {
                if ((executionContext.LanguageMode == PSLanguageMode.NoLanguage) &&
                    (origin == Automation.CommandOrigin.Runspace))
                {
                    throw InterpreterError.NewInterpreterException(CommandText, typeof(ParseException),
                                                                   null, "ScriptsNotAllowed", ParserStrings.ScriptsNotAllowed);
                }

                ScriptBlock scriptBlock = executionContext.Engine.ParseScriptBlock(CommandText, addToHistory);
                if (origin == Automation.CommandOrigin.Internal)
                {
                    scriptBlock.LanguageMode = PSLanguageMode.FullLanguage;
                }

                // If running in restricted language mode, verify that the parse tree represents on legitimate
                // constructions...
                switch (scriptBlock.LanguageMode)
                {
                case PSLanguageMode.RestrictedLanguage:
                    scriptBlock.CheckRestrictedLanguage(null, null, false);
                    break;

                case PSLanguageMode.FullLanguage:
                    // Interactive script commands are permitted in this mode.
                    break;

                case PSLanguageMode.ConstrainedLanguage:
                    // Constrained Language is checked at runtime.
                    break;

                default:
                    // This should never happen...
                    Diagnostics.Assert(false, "Invalid langage mode was set when building a ScriptCommandProcessor");
                    throw new InvalidOperationException("Invalid langage mode was set when building a ScriptCommandProcessor");
                }

                if (scriptBlock.UsesCmdletBinding)
                {
                    FunctionInfo functionInfo = new FunctionInfo("", scriptBlock, executionContext);
                    commandProcessorBase = new CommandProcessor(functionInfo, executionContext,
                                                                _useLocalScope ?? false, fromScriptFile: false, sessionState: executionContext.EngineSessionState);
                }
                else
                {
                    commandProcessorBase = new DlrScriptCommandProcessor(scriptBlock,
                                                                         executionContext, _useLocalScope ?? false,
                                                                         origin,
                                                                         executionContext.EngineSessionState);
                }
            }
            else
            {
                // RestrictedLanguage / NoLanguage do not support dot-sourcing when CommandOrigin is Runspace
                if ((_useLocalScope.HasValue) && (!_useLocalScope.Value))
                {
                    switch (executionContext.LanguageMode)
                    {
                    case PSLanguageMode.RestrictedLanguage:
                    case PSLanguageMode.NoLanguage:
                        string message = StringUtil.Format(RunspaceStrings.UseLocalScopeNotAllowed,
                                                           "UseLocalScope",
                                                           PSLanguageMode.RestrictedLanguage.ToString(),
                                                           PSLanguageMode.NoLanguage.ToString());
                        throw new RuntimeException(message);

                    case PSLanguageMode.FullLanguage:
                        // Interactive script commands are permitted in this mode...
                        break;
                    }
                }

                commandProcessorBase =
                    commandFactory.CreateCommand(CommandText, origin, _useLocalScope);
            }

            CommandParameterCollection parameters = Parameters;

            if (parameters != null)
            {
                bool isNativeCommand = commandProcessorBase is NativeCommandProcessor;
                foreach (CommandParameter publicParameter in parameters)
                {
                    CommandParameterInternal internalParameter = CommandParameter.ToCommandParameterInternal(publicParameter, isNativeCommand);
                    commandProcessorBase.AddParameter(internalParameter);
                }
            }

            string       helpTarget;
            HelpCategory helpCategory;

            if (commandProcessorBase.IsHelpRequested(out helpTarget, out helpCategory))
            {
                commandProcessorBase = CommandProcessorBase.CreateGetHelpCommandProcessor(
                    executionContext,
                    helpTarget,
                    helpCategory);
            }

            //Set the merge settings
            SetMergeSettingsOnCommandProcessor(commandProcessorBase);

            return(commandProcessorBase);
        }
예제 #11
0
        protected override void ProcessRecord()
        {
            ProviderInfo        provider = null;
            Collection <string> resolvedProviderPathFromPSPath;

            try
            {
                if (base.Context.EngineSessionState.IsProviderLoaded(base.Context.ProviderNames.FileSystem))
                {
                    resolvedProviderPathFromPSPath = base.SessionState.Path.GetResolvedProviderPathFromPSPath(this.path, out provider);
                }
                else
                {
                    resolvedProviderPathFromPSPath = new Collection <string> {
                        this.path
                    };
                }
            }
            catch (ItemNotFoundException)
            {
                FileNotFoundException exception   = new FileNotFoundException(StringUtil.Format(RemotingErrorIdStrings.PSSessionConfigurationFileNotFound, this.path));
                ErrorRecord           errorRecord = new ErrorRecord(exception, "PSSessionConfigurationFileNotFound", ErrorCategory.ResourceUnavailable, this.path);
                base.WriteError(errorRecord);
                return;
            }
            if (!provider.NameEquals(base.Context.ProviderNames.FileSystem))
            {
                throw InterpreterError.NewInterpreterException(this.path, typeof(RuntimeException), null, "FileOpenError", ParserStrings.FileOpenError, new object[] { provider.FullName });
            }
            if ((resolvedProviderPathFromPSPath != null) && (resolvedProviderPathFromPSPath.Count >= 1))
            {
                if (resolvedProviderPathFromPSPath.Count > 1)
                {
                    throw InterpreterError.NewInterpreterException(resolvedProviderPathFromPSPath, typeof(RuntimeException), null, "AmbiguousPath", ParserStrings.AmbiguousPath, new object[0]);
                }
                string             path       = resolvedProviderPathFromPSPath[0];
                ExternalScriptInfo scriptInfo = null;
                if (System.IO.Path.GetExtension(path).Equals(".pssc", StringComparison.OrdinalIgnoreCase))
                {
                    string str5;
                    scriptInfo = DISCUtils.GetScriptInfoForFile(base.Context, path, out str5);
                    Hashtable table = null;
                    try
                    {
                        table = DISCUtils.LoadConfigFile(base.Context, scriptInfo);
                    }
                    catch (RuntimeException exception3)
                    {
                        base.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.DISCErrorParsingConfigFile, path, exception3.Message));
                        base.WriteObject(false);
                        return;
                    }
                    if (table == null)
                    {
                        base.WriteObject(false);
                    }
                    else
                    {
                        DISCUtils.ExecutionPolicyType = typeof(ExecutionPolicy);
                        base.WriteObject(DISCUtils.VerifyConfigTable(table, this, path));
                    }
                }
                else
                {
                    InvalidOperationException exception4 = new InvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.InvalidPSSessionConfigurationFilePath, path));
                    ErrorRecord record3 = new ErrorRecord(exception4, "InvalidPSSessionConfigurationFilePath", ErrorCategory.InvalidArgument, this.path);
                    base.ThrowTerminatingError(record3);
                }
            }
            else
            {
                FileNotFoundException exception2 = new FileNotFoundException(StringUtil.Format(RemotingErrorIdStrings.PSSessionConfigurationFileNotFound, this.path));
                ErrorRecord           record2    = new ErrorRecord(exception2, "PSSessionConfigurationFileNotFound", ErrorCategory.ResourceUnavailable, this.path);
                base.WriteError(record2);
            }
        }
예제 #12
0
        /// <summary>
        /// Implements the record processing for this cmdlet.
        /// </summary>
        protected override void ProcessRecord()
        {
            ProviderInfo        provider = null;
            Collection <string> filePaths;

            try
            {
                if (Context.EngineSessionState.IsProviderLoaded(Context.ProviderNames.FileSystem))
                {
                    filePaths =
                        SessionState.Path.GetResolvedProviderPathFromPSPath(_path, out provider);
                }
                else
                {
                    filePaths = new Collection <string>();
                    filePaths.Add(_path);
                }
            }
            catch (ItemNotFoundException)
            {
                string message            = StringUtil.Format(Modules.ModuleNotFound, _path);
                FileNotFoundException fnf = new FileNotFoundException(message);
                ErrorRecord           er  = new ErrorRecord(fnf, "Modules_ModuleNotFound",
                                                            ErrorCategory.ResourceUnavailable, _path);
                WriteError(er);
                return;
            }

            // Make sure that the path is in the file system - that's all we can handle currently...
            if (!provider.NameEquals(this.Context.ProviderNames.FileSystem))
            {
                // "The current provider ({0}) cannot open a file"
                throw InterpreterError.NewInterpreterException(_path, typeof(RuntimeException),
                                                               null, "FileOpenError", ParserStrings.FileOpenError, provider.FullName);
            }

            // Make sure at least one file was found...
            if (filePaths == null || filePaths.Count < 1)
            {
                string message            = StringUtil.Format(Modules.ModuleNotFound, _path);
                FileNotFoundException fnf = new FileNotFoundException(message);
                ErrorRecord           er  = new ErrorRecord(fnf, "Modules_ModuleNotFound",
                                                            ErrorCategory.ResourceUnavailable, _path);
                WriteError(er);
                return;
            }

            if (filePaths.Count > 1)
            {
                // "The path resolved to more than one file; can only process one file at a time."
                throw InterpreterError.NewInterpreterException(filePaths, typeof(RuntimeException),
                                                               null, "AmbiguousPath", ParserStrings.AmbiguousPath);
            }

            string             filePath   = filePaths[0];
            ExternalScriptInfo scriptInfo = null;
            string             ext        = System.IO.Path.GetExtension(filePath);

            if (ext.Equals(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
            {
                // Create a script info for loading the file...
                string scriptName;
                scriptInfo = GetScriptInfoForFile(filePath, out scriptName, false);

                // we should reserve the Context.ModuleBeingProcessed unchanged after loadModuleManifest(), otherwise the module won't be importable next time.
                PSModuleInfo module;
                string       _origModuleBeingProcessed = Context.ModuleBeingProcessed;
                try
                {
                    module = LoadModuleManifest(
                        scriptInfo,
                        ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings /* but don't stop on first error and don't load elements */,
                        null,
                        null,
                        null,
                        null);

                    if (module != null)
                    {
                        // Validate file existence
                        if (module.RequiredAssemblies != null)
                        {
                            foreach (string requiredAssembliespath in module.RequiredAssemblies)
                            {
                                if (!IsValidFilePath(requiredAssembliespath, module, true) && !IsValidGacAssembly(requiredAssembliespath))
                                {
                                    string errorMsg    = StringUtil.Format(Modules.InvalidRequiredAssembliesInModuleManifest, requiredAssembliespath, filePath);
                                    var    errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidRequiredAssembliesInModuleManifest",
                                                                         ErrorCategory.ObjectNotFound, _path);
                                    WriteError(errorRecord);
                                }
                            }
                        }

                        if (!HasValidRootModule(module))
                        {
                            string errorMsg    = StringUtil.Format(Modules.InvalidModuleManifest, module.RootModule, filePath);
                            var    errorRecord = new ErrorRecord(new ArgumentException(errorMsg), "Modules_InvalidRootModuleInModuleManifest",
                                                                 ErrorCategory.InvalidArgument, _path);
                            WriteError(errorRecord);
                        }

                        Hashtable data            = null;
                        Hashtable localizedData   = null;
                        bool      containerErrors = false;
                        LoadModuleManifestData(scriptInfo, ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out data, out localizedData, ref containerErrors);
                        ModuleSpecification[] nestedModules;
                        GetScalarFromData(data, scriptInfo.Path, "NestedModules", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out nestedModules);
                        if (nestedModules != null)
                        {
                            foreach (ModuleSpecification nestedModule in nestedModules)
                            {
                                if (!IsValidFilePath(nestedModule.Name, module, true) &&
                                    !IsValidFilePath(nestedModule.Name + StringLiterals.PowerShellILAssemblyExtension, module, true) &&
                                    !IsValidFilePath(nestedModule.Name + StringLiterals.PowerShellNgenAssemblyExtension, module, true) &&
                                    !IsValidFilePath(nestedModule.Name + StringLiterals.PowerShellILExecutableExtension, module, true) &&
                                    !IsValidFilePath(nestedModule.Name + StringLiterals.PowerShellModuleFileExtension, module, true) &&
                                    !IsValidGacAssembly(nestedModule.Name))
                                {
                                    Collection <PSModuleInfo> modules = GetModuleIfAvailable(nestedModule);
                                    if (0 == modules.Count)
                                    {
                                        string errorMsg    = StringUtil.Format(Modules.InvalidNestedModuleinModuleManifest, nestedModule.Name, filePath);
                                        var    errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidNestedModuleinModuleManifest",
                                                                             ErrorCategory.ObjectNotFound, _path);
                                        WriteError(errorRecord);
                                    }
                                }
                            }
                        }

                        ModuleSpecification[] requiredModules;
                        GetScalarFromData(data, scriptInfo.Path, "RequiredModules", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out requiredModules);
                        if (requiredModules != null)
                        {
                            foreach (ModuleSpecification requiredModule in requiredModules)
                            {
                                var modules = GetModule(new[] { requiredModule.Name }, all: false, refresh: true);
                                if (modules.Count == 0)
                                {
                                    string errorMsg    = StringUtil.Format(Modules.InvalidRequiredModulesinModuleManifest, requiredModule.Name, filePath);
                                    var    errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidRequiredModulesinModuleManifest",
                                                                         ErrorCategory.ObjectNotFound, _path);
                                    WriteError(errorRecord);
                                }
                            }
                        }

                        string[] fileListPaths;
                        GetScalarFromData(data, scriptInfo.Path, "FileList", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out fileListPaths);
                        if (fileListPaths != null)
                        {
                            foreach (string fileListPath in fileListPaths)
                            {
                                if (!IsValidFilePath(fileListPath, module, true))
                                {
                                    string errorMsg    = StringUtil.Format(Modules.InvalidFilePathinModuleManifest, fileListPath, filePath);
                                    var    errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidFilePathinModuleManifest",
                                                                         ErrorCategory.ObjectNotFound, _path);
                                    WriteError(errorRecord);
                                }
                            }
                        }

                        ModuleSpecification[] moduleListModules;
                        GetScalarFromData(data, scriptInfo.Path, "ModuleList", ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.WriteWarnings, out moduleListModules);
                        if (moduleListModules != null)
                        {
                            foreach (ModuleSpecification moduleListModule in moduleListModules)
                            {
                                var modules = GetModule(new[] { moduleListModule.Name }, all: false, refresh: true);
                                if (modules.Count == 0)
                                {
                                    string errorMsg    = StringUtil.Format(Modules.InvalidModuleListinModuleManifest, moduleListModule.Name, filePath);
                                    var    errorRecord = new ErrorRecord(new DirectoryNotFoundException(errorMsg), "Modules_InvalidModuleListinModuleManifest",
                                                                         ErrorCategory.ObjectNotFound, _path);
                                    WriteError(errorRecord);
                                }
                            }
                        }

                        if (module.CompatiblePSEditions.Any())
                        {
                            // The CompatiblePSEditions module manifest key is supported only on PowerShell version '5.1' or higher.
                            // Ensure that PowerShellVersion module manifest key value is '5.1' or higher.
                            //
                            var minimumRequiredPowerShellVersion = new Version(5, 1);
                            if ((module.PowerShellVersion == null) || module.PowerShellVersion < minimumRequiredPowerShellVersion)
                            {
                                string errorMsg    = StringUtil.Format(Modules.InvalidPowerShellVersionInModuleManifest, filePath);
                                var    errorRecord = new ErrorRecord(new ArgumentException(errorMsg), "Modules_InvalidPowerShellVersionInModuleManifest", ErrorCategory.InvalidArgument, _path);
                                WriteError(errorRecord);
                            }
                        }
                    }
                }
                finally
                {
                    Context.ModuleBeingProcessed = _origModuleBeingProcessed;
                }

                DirectoryInfo parent = null;
                try
                {
                    parent = Directory.GetParent(filePath);
                }
                catch (IOException) { }
                catch (UnauthorizedAccessException) { }
                catch (ArgumentException) { }

                Version version;
                if (parent != null && Version.TryParse(parent.Name, out version))
                {
                    if (!version.Equals(module.Version))
                    {
                        string      message = StringUtil.Format(Modules.InvalidModuleManifestVersion, filePath, module.Version.ToString(), parent.FullName);
                        var         ioe     = new InvalidOperationException(message);
                        ErrorRecord er      = new ErrorRecord(ioe, "Modules_InvalidModuleManifestVersion",
                                                              ErrorCategory.InvalidArgument, _path);
                        ThrowTerminatingError(er);
                    }

                    WriteVerbose(Modules.ModuleVersionEqualsToVersionFolder);
                }

                if (module != null)
                {
                    WriteObject(module);
                }
            }
            else
            {
                string message = StringUtil.Format(Modules.InvalidModuleManifestPath, filePath);
                InvalidOperationException ioe = new InvalidOperationException(message);
                ErrorRecord er = new ErrorRecord(ioe, "Modules_InvalidModuleManifestPath",
                                                 ErrorCategory.InvalidArgument, _path);
                ThrowTerminatingError(er);
            }
        }
예제 #13
0
        internal CommandProcessorBase CreateCommandProcessor(ExecutionContext executionContext, CommandFactory commandFactory, bool addToHistory, CommandOrigin origin)
        {
            CommandProcessorBase base2;
            string       str2;
            HelpCategory category;

            if (!this.IsScript)
            {
                if (this._useLocalScope.HasValue && !this._useLocalScope.Value)
                {
                    switch (executionContext.LanguageMode)
                    {
                    case PSLanguageMode.RestrictedLanguage:
                    case PSLanguageMode.NoLanguage:
                        throw new RuntimeException(StringUtil.Format(RunspaceStrings.UseLocalScopeNotAllowed, new object[] { "UseLocalScope", PSLanguageMode.RestrictedLanguage.ToString(), PSLanguageMode.NoLanguage.ToString() }));
                    }
                }
                base2 = commandFactory.CreateCommand(this.CommandText, origin, this._useLocalScope);
            }
            else
            {
                if (executionContext.LanguageMode == PSLanguageMode.NoLanguage)
                {
                    throw InterpreterError.NewInterpreterException(this.CommandText, typeof(ParseException), null, "ScriptsNotAllowed", ParserStrings.ScriptsNotAllowed, new object[0]);
                }
                ScriptBlock function = executionContext.Engine.ParseScriptBlock(this.CommandText, addToHistory);
                switch (executionContext.LanguageMode)
                {
                case PSLanguageMode.FullLanguage:
                case PSLanguageMode.ConstrainedLanguage:
                    break;

                case PSLanguageMode.RestrictedLanguage:
                    function.CheckRestrictedLanguage(null, null, false);
                    break;

                default:
                    throw new InvalidOperationException("Invalid langage mode was set when building a ScriptCommandProcessor");
                }
                if (function.UsesCmdletBinding)
                {
                    FunctionInfo scriptCommandInfo = new FunctionInfo("", function, executionContext);
                    bool?        nullable          = this._useLocalScope;
                    base2 = new CommandProcessor(scriptCommandInfo, executionContext, nullable.HasValue ? nullable.GetValueOrDefault() : false, false, executionContext.EngineSessionState);
                }
                else
                {
                    bool?nullable2 = this._useLocalScope;
                    base2 = new DlrScriptCommandProcessor(function, executionContext, nullable2.HasValue ? nullable2.GetValueOrDefault() : false, CommandOrigin.Runspace, executionContext.EngineSessionState);
                }
            }
            CommandParameterCollection parameters = this.Parameters;

            if (parameters != null)
            {
                bool forNativeCommand = base2 is NativeCommandProcessor;
                foreach (CommandParameter parameter in parameters)
                {
                    CommandParameterInternal internal2 = CommandParameter.ToCommandParameterInternal(parameter, forNativeCommand);
                    base2.AddParameter(internal2);
                }
            }
            if (base2.IsHelpRequested(out str2, out category))
            {
                base2 = CommandProcessorBase.CreateGetHelpCommandProcessor(executionContext, str2, category);
            }
            this.SetMergeSettingsOnCommandProcessor(base2);
            return(base2);
        }
        /// <summary>
        /// Perform disambiguation on enum names.
        /// </summary>
        /// <returns>Complete enum name after disambiguation.</returns>
        internal static string EnumDisambiguate(string text, Type enumType)
        {
            // Get all enum names in the given enum type
            string[] enumNames = Enum.GetNames(enumType);

            // Get all names that matches the given prefix.
            List <string> namesWithMatchingPrefix = new List <string>();

            foreach (string name in enumNames)
            {
                if (name.StartsWith(text, StringComparison.OrdinalIgnoreCase))
                {
                    namesWithMatchingPrefix.Add(name);
                }
            }

            // Throw error when no match is found.
            if (namesWithMatchingPrefix.Count == 0)
            {
                throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException),
                                                               null, "NoEnumNameMatch", EnumExpressionEvaluatorStrings.NoEnumNameMatch, text, EnumAllValues(enumType));
            }
            // Return the result if there is only one match.
            else if (namesWithMatchingPrefix.Count == 1)
            {
                return(namesWithMatchingPrefix[0]);
            }
            // multiple matches situation
            else
            {
                // test for exact match
                foreach (string matchName in namesWithMatchingPrefix)
                {
                    if (matchName.Equals(text, StringComparison.OrdinalIgnoreCase))
                    {
                        return(matchName);
                    }
                }
                // test for special cases match
                string[] minDisambiguateNames;
                if (s_specialDisambiguateCases.TryGetValue(enumType, out minDisambiguateNames))
                {
                    foreach (string tName in minDisambiguateNames)
                    {
                        if (tName.StartsWith(text, StringComparison.OrdinalIgnoreCase))
                        {
                            return(tName);
                        }
                    }
                }
                // No special cases match, throw error for multiple matches.
                StringBuilder matchListSB = new StringBuilder(namesWithMatchingPrefix[0]);
                const string  separator   = ", ";
                for (int i = 1; i < namesWithMatchingPrefix.Count; i++)
                {
                    matchListSB.Append(separator);
                    matchListSB.Append(namesWithMatchingPrefix[i]);
                }

                throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException),
                                                               null, "MultipleEnumNameMatch", EnumExpressionEvaluatorStrings.MultipleEnumNameMatch,
                                                               text, matchListSB.ToString());
            }
        }
예제 #15
0
        /// <summary>
        /// Given the start (offset) of the next token, traverse through
        /// the string to find the next token, stripping correctly
        /// enclosed quotes.
        /// </summary>
        /// <param name="input">
        /// Input string
        /// </param>
        /// <param name="_offset">
        /// Current offset position for the string parser.
        /// </param>
        /// <returns>
        /// The next token on the input string
        /// </returns>
        private static Token GetNextToken(string input, ref int _offset)
        {
            StringBuilder sb = new StringBuilder();
            // bool singleQuoted = false;
            // bool doubleQuoted = false;
            bool readingIdentifier = false;

            while (_offset < input.Length)
            {
                char cc = input[_offset++];
                if ((cc == ',') || (cc == '+') || (cc == '!'))
                {
                    if (!readingIdentifier)
                    {
                        sb.Append(cc);
                    }
                    else
                    {
                        _offset--;
                    }

                    break;
                }
                else
                {
                    sb.Append(cc);
                    readingIdentifier = true;
                }
            }

            string result = sb.ToString().Trim();

            // If resulting identifier is enclosed in paired quotes,
            // remove the only the first pair of quotes from the string
            if (result.Length >= 2 &&
                ((result[0] == '\'' && result[result.Length - 1] == '\'') ||
                 (result[0] == '\"' && result[result.Length - 1] == '\"')))
            {
                result = result.Substring(1, result.Length - 2);
            }

            result = result.Trim();

            // possible empty token because white spaces are enclosed in quotation marks.
            if (string.IsNullOrWhiteSpace(result))
            {
                throw InterpreterError.NewInterpreterException(input, typeof(RuntimeException),
                                                               null, "EmptyTokenString", EnumExpressionEvaluatorStrings.EmptyTokenString,
                                                               EnumMinimumDisambiguation.EnumAllValues(typeof(T)));
            }
            else if (result[0] == '(')
            {
                int matchIndex = input.IndexOf(')', _offset);
                if (result[result.Length - 1] == ')' || matchIndex >= 0)
                {
                    throw InterpreterError.NewInterpreterException(input, typeof(RuntimeException),
                                                                   null, "NoIdentifierGroupingAllowed", EnumExpressionEvaluatorStrings.NoIdentifierGroupingAllowed);
                }
            }

            if (result.Equals(","))
            {
                return(new Token(TokenKind.Or));
            }
            else if (result.Equals("+"))
            {
                return(new Token(TokenKind.And));
            }
            else if (result.Equals("!"))
            {
                return(new Token(TokenKind.Not));
            }
            else
            {
                return(new Token(result));
            }
        }
        protected override void ProcessRecord()
        {
            ProviderInfo        provider = null;
            Collection <string> resolvedProviderPathFromPSPath;

            try
            {
                if (base.Context.EngineSessionState.IsProviderLoaded(base.Context.ProviderNames.FileSystem))
                {
                    resolvedProviderPathFromPSPath = base.SessionState.Path.GetResolvedProviderPathFromPSPath(this._path, out provider);
                }
                else
                {
                    resolvedProviderPathFromPSPath = new Collection <string> {
                        this._path
                    };
                }
            }
            catch (ItemNotFoundException)
            {
                FileNotFoundException exception   = new FileNotFoundException(StringUtil.Format(Modules.ModuleNotFound, this._path));
                ErrorRecord           errorRecord = new ErrorRecord(exception, "Modules_ModuleNotFound", ErrorCategory.ResourceUnavailable, this._path);
                base.WriteError(errorRecord);
                return;
            }
            if (!provider.NameEquals(base.Context.ProviderNames.FileSystem))
            {
                throw InterpreterError.NewInterpreterException(this._path, typeof(RuntimeException), null, "FileOpenError", ParserStrings.FileOpenError, new object[] { provider.FullName });
            }
            if ((resolvedProviderPathFromPSPath != null) && (resolvedProviderPathFromPSPath.Count >= 1))
            {
                if (resolvedProviderPathFromPSPath.Count > 1)
                {
                    throw InterpreterError.NewInterpreterException(resolvedProviderPathFromPSPath, typeof(RuntimeException), null, "AmbiguousPath", ParserStrings.AmbiguousPath, new object[0]);
                }
                string             path       = resolvedProviderPathFromPSPath[0];
                ExternalScriptInfo scriptInfo = null;
                if (System.IO.Path.GetExtension(path).Equals(".psd1", StringComparison.OrdinalIgnoreCase))
                {
                    string str5;
                    scriptInfo = base.GetScriptInfoForFile(path, out str5, false);
                    PSModuleInfo sendToPipeline = base.LoadModuleManifest(scriptInfo, ModuleCmdletBase.ManifestProcessingFlags.WriteWarnings | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors, null, null);
                    if (sendToPipeline != null)
                    {
                        base.WriteObject(sendToPipeline);
                    }
                }
                else
                {
                    InvalidOperationException exception3 = new InvalidOperationException(StringUtil.Format(Modules.InvalidModuleManifestPath, path));
                    ErrorRecord record3 = new ErrorRecord(exception3, "Modules_InvalidModuleManifestPath", ErrorCategory.InvalidArgument, this._path);
                    base.ThrowTerminatingError(record3);
                }
            }
            else
            {
                FileNotFoundException exception2 = new FileNotFoundException(StringUtil.Format(Modules.ModuleNotFound, this._path));
                ErrorRecord           record2    = new ErrorRecord(exception2, "Modules_ModuleNotFound", ErrorCategory.ResourceUnavailable, this._path);
                base.WriteError(record2);
            }
        }