Ejemplo n.º 1
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);
            }
        }
Ejemplo n.º 2
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);
            }
        }
Ejemplo n.º 3
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);
        }
Ejemplo n.º 4
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);
            }
        }
Ejemplo n.º 5
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());
            }
        }
Ejemplo n.º 7
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);
            }
        }