Beispiel #1
0
        //actual constructor work, but hidden to not be used accidently in a stupid way
        private SessionState(SessionStateGlobal sessionStateGlobal, SessionState parent)
        {
            SessionStateGlobal = sessionStateGlobal;

            var parentAliasScope    = parent == null ? null : parent._aliasScope;
            var parentFunctionScope = parent == null ? null : parent._functionScope;
            var parentVariableScope = parent == null ? null : parent._variableScope;
            var parentDriveScope    = parent == null ? null : parent._driveScope;
            var parentModuleScope   = parent == null ? null : parent._moduleScope;
            var parentCmdletScope   = parent == null ? null : parent._cmdletScope;

            _aliasScope    = new SessionStateScope <AliasInfo>(this, parentAliasScope, SessionStateCategory.Alias);
            _functionScope = new SessionStateScope <FunctionInfo>(this, parentFunctionScope, SessionStateCategory.Function);
            _variableScope = new SessionStateScope <PSVariable>(this, parentVariableScope, SessionStateCategory.Variable);
            _driveScope    = new SessionStateScope <PSDriveInfo>(this, parentDriveScope, SessionStateCategory.Drive);
            _moduleScope   = new SessionStateScope <PSModuleInfo>(this, parentModuleScope, SessionStateCategory.Module);
            _cmdletScope   = new SessionStateScope <CmdletInfo>(this, parentCmdletScope, SessionStateCategory.Cmdlet);

            IsScriptScope = false;
            Function      = new FunctionIntrinsics(_functionScope);
            Alias         = new AliasIntrinsics(_aliasScope);

            Drive         = new DriveManagementIntrinsics(_driveScope);
            Path          = new PathIntrinsics(this);
            PSVariable    = new PSVariableIntrinsics(_variableScope);
            LoadedModules = new ModuleIntrinsics(_moduleScope);
            Cmdlet        = new CmdletIntrinsics(_cmdletScope);
        }
Beispiel #2
0
        internal static string GetModuleName(string path)
        {
            string path1     = path == null ? string.Empty : Path.GetFileName(path);
            string extension = Path.GetExtension(path1);

            return(!string.IsNullOrEmpty(extension) && ModuleIntrinsics.IsPowerShellModuleExtension(extension) ? path1.Substring(0, path1.Length - extension.Length) : path1);
        }
Beispiel #3
0
 private void InitializeCommon(AutomationEngine engine, PSHost hostInterface)
 {
     this._engine = engine;
     if (!_assemblyEventHandlerSet)
     {
         lock (lockObject)
         {
             if (!_assemblyEventHandlerSet)
             {
                 AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(ExecutionContext.PowerShellAssemblyResolveHandler);
                 _assemblyEventHandlerSet = true;
             }
         }
     }
     this._debugger          = new System.Management.Automation.Debugger(this);
     this.eventManager       = new PSLocalEventManager(this);
     this.transactionManager = new PSTransactionManager();
     this.myHostInterface    = hostInterface as System.Management.Automation.Internal.Host.InternalHost;
     if (this.myHostInterface == null)
     {
         this.myHostInterface = new System.Management.Automation.Internal.Host.InternalHost(hostInterface, this);
     }
     this._assemblyCache        = new Dictionary <string, Assembly>();
     this._topLevelSessionState = this._engineSessionState = new SessionStateInternal(this);
     if (this._authorizationManager == null)
     {
         this._authorizationManager = new System.Management.Automation.AuthorizationManager(null);
     }
     this._modules = new ModuleIntrinsics(this);
 }
        /// <summary>
        /// Gets the extended search paths for about_topics help. To be able to get about_topics help from unloaded modules,
        /// we will add $pshome and the folders under PS module paths to the collection of paths to search.
        /// </summary>
        /// <returns>A collection of string representing locations.</returns>
        internal Collection <string> GetExtendedSearchPaths()
        {
            Collection <string> searchPaths = GetSearchPaths();

            // Add $pshome at the top of the list
            string defaultShellSearchPath = GetDefaultShellSearchPath();

            int index = searchPaths.IndexOf(defaultShellSearchPath);

            if (index != 0)
            {
                if (index > 0)
                {
                    searchPaths.RemoveAt(index);
                }

                searchPaths.Insert(0, defaultShellSearchPath);
            }

            // Add the CurrentUser help path.
            searchPaths.Add(HelpUtils.GetUserHomeHelpSearchPath());

            // Add modules that are not loaded. Since using 'get-module -listavailable' is very expensive,
            // we load all the directories (which are not empty) under the module path.
            foreach (string psModulePath in ModuleIntrinsics.GetModulePath(false, this.HelpSystem.ExecutionContext))
            {
                if (Directory.Exists(psModulePath))
                {
                    try
                    {
                        // Get all the directories under the module path
                        // * and SearchOption.AllDirectories gets all the version directories.
                        string[] directories = Directory.GetDirectories(psModulePath, "*", SearchOption.AllDirectories);

                        var possibleModuleDirectories = directories.Where(static directory => !ModuleUtils.IsPossibleResourceDirectory(directory));
        /// <summary>
        /// Gets the extended search paths for about_topics help. To be able to get about_topics help from unloaded modules,
        /// we will add $pshome and the folders under PS module paths to the collection of paths to search.
        /// </summary>
        /// <returns>A collection of string representing locations.</returns>
        internal Collection <string> GetExtendedSearchPaths()
        {
            Collection <string> searchPaths = GetSearchPaths();

            // Add $pshome at the top of the list
            string defaultShellSearchPath = GetDefaultShellSearchPath();

            int index = searchPaths.IndexOf(defaultShellSearchPath);

            if (index != 0)
            {
                if (index > 0)
                {
                    searchPaths.RemoveAt(index);
                }

                searchPaths.Insert(0, defaultShellSearchPath);
            }

            // Add the CurrentUser help path.
            searchPaths.Add(HelpUtils.GetUserHomeHelpSearchPath());

            // Add modules that are not loaded. Since using 'get-module -listavailable' is very expensive,
            // we load all the directories (which are not empty) under the module path.
            foreach (string psModulePath in ModuleIntrinsics.GetModulePath(false, this.HelpSystem.ExecutionContext))
            {
                if (Directory.Exists(psModulePath))
                {
                    try
                    {
                        // Get all the directories under the module path
                        // * and SearchOption.AllDirectories gets all the version directories.
                        string[] directories = Directory.GetDirectories(psModulePath, "*", SearchOption.AllDirectories);

                        var possibleModuleDirectories = directories.Where(directory => !ModuleUtils.IsPossibleResourceDirectory(directory));

                        foreach (string directory in possibleModuleDirectories)
                        {
                            // Add only directories that are not empty
                            if (Directory.EnumerateFiles(directory).Any())
                            {
                                if (!searchPaths.Contains(directory))
                                {
                                    searchPaths.Add(directory);
                                }
                            }
                        }
                    }
                    // Absorb any exception related to enumerating directories
                    catch (System.ArgumentException) { }
                    catch (System.IO.IOException) { }
                    catch (System.UnauthorizedAccessException) { }
                    catch (System.Security.SecurityException) { }
                }
            }

            return(searchPaths);
        }
Beispiel #6
0
 internal PSModuleInfo CreateModule(
     string path,
     ExternalScriptInfo scriptInfo,
     Token callerToken,
     SessionState ss,
     params object[] arguments)
 {
     return(this.CreateModuleImplementation(ModuleIntrinsics.GetModuleName(path), path, (object)scriptInfo, callerToken, ss, out ArrayList _, arguments));
 }
 /// <summary>
 /// Gets the specified module path from the appropriate Environment entry in the registry.
 /// </summary>
 /// <param name="scope"></param>
 /// <returns>The specified module path. Null if not present.</returns>
 internal override string GetModulePath(PropertyScope scope)
 {
     if (PropertyScope.CurrentUser == scope)
     {
         return(ModuleIntrinsics.GetExpandedEnvironmentVariable("PSMODULEPATH", EnvironmentVariableTarget.User));
     }
     else
     {
         return(ModuleIntrinsics.GetExpandedEnvironmentVariable("PSMODULEPATH", EnvironmentVariableTarget.Machine));
     }
 }
Beispiel #8
0
        internal static void SetModulePath()
        {
            string environmentVariable1 = ModuleIntrinsics.GetExpandedEnvironmentVariable("PSMODULEPATH", EnvironmentVariableTarget.Process);
            string environmentVariable2 = ModuleIntrinsics.GetExpandedEnvironmentVariable("PSMODULEPATH", EnvironmentVariableTarget.Machine);
            string environmentVariable3 = ModuleIntrinsics.GetExpandedEnvironmentVariable("PSMODULEPATH", EnvironmentVariableTarget.User);
            string str1;

            if (environmentVariable1 == null)
            {
                string str2 = (environmentVariable3 ?? ModuleIntrinsics.GetPersonalModulePath()) + (object)';';
                str1 = environmentVariable2 != null ? str2 + environmentVariable2 : str2 + ModuleIntrinsics.GetSystemwideModulePath();
            }
            else if (environmentVariable2 != null)
            {
                if (environmentVariable3 == null)
                {
                    if (!environmentVariable2.Equals(environmentVariable1, StringComparison.OrdinalIgnoreCase))
                    {
                        return;
                    }
                    str1 = ModuleIntrinsics.GetPersonalModulePath() + (object)';' + environmentVariable2;
                }
                else
                {
                    string str2 = environmentVariable3 + (object)';' + environmentVariable2;
                    if (!str2.Equals(environmentVariable1, StringComparison.OrdinalIgnoreCase) && !environmentVariable2.Equals(environmentVariable1, StringComparison.OrdinalIgnoreCase) && !environmentVariable3.Equals(environmentVariable1, StringComparison.OrdinalIgnoreCase))
                    {
                        return;
                    }
                    str1 = str2;
                }
            }
            else
            {
                if (environmentVariable3 == null || !environmentVariable3.Equals(environmentVariable1, StringComparison.OrdinalIgnoreCase))
                {
                    return;
                }
                str1 = environmentVariable3 + (object)';' + ModuleIntrinsics.GetSystemwideModulePath();
            }
            Environment.SetEnvironmentVariable("PSMODULEPATH", str1);
        }
Beispiel #9
0
 internal PSModuleInfo(
     string name,
     string path,
     ExecutionContext context,
     SessionState sessionState)
 {
     this._context = context;
     if (path != null)
     {
         string resolvedPath = ModuleCmdletBase.GetResolvedPath(path, this._context);
         this._path = resolvedPath == null ? path : resolvedPath;
     }
     this._name         = name != null || this._path == null ? name : ModuleIntrinsics.GetModuleName(this._path);
     this._sessionState = sessionState;
     if (sessionState == null)
     {
         return;
     }
     sessionState.Internal.Module = this;
 }
Beispiel #10
0
 internal PSModuleInfo(string name, string path, ExecutionContext context, System.Management.Automation.SessionState sessionState)
 {
     this._name                         = string.Empty;
     this._path                         = string.Empty;
     this._description                  = string.Empty;
     this._version                      = new System.Version(0, 0);
     this._detectedFunctionExports      = new List <string>();
     this._detectedWorkflowExports      = new List <string>();
     this._detectedCmdletExports        = new List <string>();
     this._compiledExports              = new List <CmdletInfo>();
     this._fileList                     = new List <string>();
     this._moduleList                   = new Collection <object>();
     this._nestedModules                = new List <PSModuleInfo>();
     this._scripts                      = new List <string>();
     this._requiredAssemblies           = new Collection <string>();
     this._requiredModules              = new List <PSModuleInfo>();
     this._requiredModulesSpecification = new List <ModuleSpecification>();
     this._detectedAliasExports         = new Dictionary <string, string>();
     this._exportedFormatFiles          = new ReadOnlyCollection <string>(new List <string>());
     this._exportedTypeFiles            = new ReadOnlyCollection <string>(new List <string>());
     if (path != null)
     {
         string resolvedPath = ModuleCmdletBase.GetResolvedPath(path, context);
         this._path = resolvedPath ?? path;
     }
     this._sessionState = sessionState;
     if (sessionState != null)
     {
         sessionState.Internal.Module = this;
     }
     if (name == null)
     {
         this._name = ModuleIntrinsics.GetModuleName(this._path);
     }
     else
     {
         this._name = name;
     }
 }
Beispiel #11
0
        internal static IEnumerable <string> GetModulePath(ExecutionContext context)
        {
            List <string> stringList          = new List <string>();
            string        environmentVariable = Environment.GetEnvironmentVariable("PSMODULEPATH");

            if (environmentVariable == null)
            {
                ModuleIntrinsics.SetModulePath();
                environmentVariable = Environment.GetEnvironmentVariable("PSMODULEPATH");
            }
            if (environmentVariable.Trim().Length == 0)
            {
                return((IEnumerable <string>)stringList);
            }
            string str1 = environmentVariable;

            char[] separator = new char[1] {
                ';'
            };
            foreach (string pattern in str1.Split(separator, StringSplitOptions.RemoveEmptyEntries))
            {
                try
                {
                    ProviderInfo         provider = (ProviderInfo)null;
                    IEnumerable <string> providerPathFromPsPath = (IEnumerable <string>)context.SessionState.Path.GetResolvedProviderPathFromPSPath(WildcardPattern.Escape(pattern), out provider);
                    if (provider.NameEquals(context.ProviderNames.FileSystem))
                    {
                        foreach (string str2 in providerPathFromPsPath)
                        {
                            stringList.Add(str2);
                        }
                    }
                }
                catch (ItemNotFoundException ex)
                {
                }
            }
            return((IEnumerable <string>)stringList);
        }
Beispiel #12
0
        internal static DirectoryInfo CreateModuleDirectory(PSCmdlet cmdlet, string moduleNameOrPath, bool force)
        {
            DirectoryInfo targetObject = null;

            try
            {
                string str = ModuleCmdletBase.ResolveRootedFilePath(moduleNameOrPath, cmdlet.Context);
                if (string.IsNullOrEmpty(str) && moduleNameOrPath.StartsWith(".", StringComparison.OrdinalIgnoreCase))
                {
                    str = Path.Combine(cmdlet.CurrentProviderLocation(cmdlet.Context.ProviderNames.FileSystem).ProviderPath, moduleNameOrPath);
                }
                if (string.IsNullOrEmpty(str))
                {
                    str = Path.Combine(ModuleIntrinsics.GetPersonalModulePath(), moduleNameOrPath);
                }
                targetObject = new DirectoryInfo(str);
                if (targetObject.Exists)
                {
                    if (!force)
                    {
                        ErrorDetails details     = new ErrorDetails(string.Format(CultureInfo.InvariantCulture, PathUtilsStrings.ExportPSSession_ErrorDirectoryExists, new object[] { targetObject.FullName }));
                        ErrorRecord  errorRecord = new ErrorRecord(new ArgumentException(details.Message), "ExportProxyCommand_OutputDirectoryExists", ErrorCategory.ResourceExists, targetObject);
                        cmdlet.ThrowTerminatingError(errorRecord);
                    }
                    return(targetObject);
                }
                targetObject.Create();
            }
            catch (Exception exception)
            {
                CommandProcessorBase.CheckForSevereException(exception);
                ErrorDetails details2 = new ErrorDetails(string.Format(CultureInfo.InvariantCulture, PathUtilsStrings.ExportPSSession_CannotCreateOutputDirectory, new object[] { moduleNameOrPath, exception.Message }));
                ErrorRecord  record2  = new ErrorRecord(new ArgumentException(details2.Message, exception), "ExportProxyCommand_CannotCreateOutputDirectory", ErrorCategory.ResourceExists, moduleNameOrPath);
                cmdlet.ThrowTerminatingError(record2);
            }
            return(targetObject);
        }
Beispiel #13
0
        internal static DirectoryInfo CreateModuleDirectory(PSCmdlet cmdlet, string moduleNameOrPath, bool force)
        {
            Dbg.Assert(cmdlet != null, "Caller should verify cmdlet != null");
            Dbg.Assert(!string.IsNullOrEmpty(moduleNameOrPath), "Caller should verify !string.IsNullOrEmpty(moduleNameOrPath)");

            DirectoryInfo directoryInfo = null;

            try
            {
                string rootedPath = Microsoft.PowerShell.Commands.ModuleCmdletBase.ResolveRootedFilePath(moduleNameOrPath, cmdlet.Context);
                if (string.IsNullOrEmpty(rootedPath) && moduleNameOrPath.StartsWith('.'))
                {
                    PathInfo currentPath = cmdlet.CurrentProviderLocation(cmdlet.Context.ProviderNames.FileSystem);
                    rootedPath = Path.Combine(currentPath.ProviderPath, moduleNameOrPath);
                }

                if (string.IsNullOrEmpty(rootedPath))
                {
                    string personalModuleRoot = ModuleIntrinsics.GetPersonalModulePath();
                    rootedPath = Path.Combine(personalModuleRoot, moduleNameOrPath);
                }

                directoryInfo = new DirectoryInfo(rootedPath);
                if (directoryInfo.Exists)
                {
                    if (!force)
                    {
                        string errorMessage = string.Format(
                            CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant
                            PathUtilsStrings.ExportPSSession_ErrorDirectoryExists,
                            directoryInfo.FullName);
                        ErrorDetails details     = new ErrorDetails(errorMessage);
                        ErrorRecord  errorRecord = new ErrorRecord(
                            new ArgumentException(details.Message),
                            "ExportProxyCommand_OutputDirectoryExists",
                            ErrorCategory.ResourceExists,
                            directoryInfo);
                        cmdlet.ThrowTerminatingError(errorRecord);
                    }
                }
                else
                {
                    directoryInfo.Create();
                }
            }
            catch (Exception e)
            {
                string errorMessage = string.Format(
                    CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant
                    PathUtilsStrings.ExportPSSession_CannotCreateOutputDirectory,
                    moduleNameOrPath,
                    e.Message);
                ErrorDetails details     = new ErrorDetails(errorMessage);
                ErrorRecord  errorRecord = new ErrorRecord(
                    new ArgumentException(details.Message, e),
                    "ExportProxyCommand_CannotCreateOutputDirectory",
                    ErrorCategory.ResourceExists,
                    moduleNameOrPath);
                cmdlet.ThrowTerminatingError(errorRecord);
            }

            return(directoryInfo);
        }
        private Collection <string> FilterToLatestModuleVersion(Collection <string> filesMatched)
        {
            Collection <string> matchedFilesToRemove = new Collection <string>();

            if (filesMatched.Count > 1)
            {
                //Dictionary<<ModuleName,fileName>, <Version, helpFileFullName>>
                Dictionary <Tuple <string, string>, Tuple <string, Version> > modulesAndVersion = new Dictionary <Tuple <string, string>, Tuple <string, Version> >();
                HashSet <string> filesProcessed = new HashSet <string>();

                var allPSModulePaths = ModuleIntrinsics.GetModulePath(false, this.HelpSystem.ExecutionContext);

                foreach (string fileFullName in filesMatched)
                {
                    // Use the filename as a check if we need to process further.
                    // Single module can have multiple .help.txt files.
                    var fileName = Path.GetFileName(fileFullName);

                    foreach (string psModulePath in allPSModulePaths)
                    {
                        Version moduleVersionFromPath = null;
                        string  moduleName            = null;
                        GetModuleNameAndVersion(psModulePath, fileFullName, out moduleName, out moduleVersionFromPath);

                        //Skip modules whose root we cannot determine or which do not have versions.
                        if (moduleVersionFromPath != null && moduleName != null)
                        {
                            Tuple <string, Version> moduleVersion = null;
                            Tuple <string, string>  key           = new Tuple <string, string>(moduleName, fileName);
                            if (modulesAndVersion.TryGetValue(key, out moduleVersion))
                            {
                                //Consider for further processing only if the help file name is same.
                                if (filesProcessed.Contains(fileName))
                                {
                                    if (moduleVersionFromPath > moduleVersion.Item2)
                                    {
                                        modulesAndVersion[key] = new Tuple <string, Version>(fileFullName, moduleVersionFromPath);

                                        //Remove the old file since we found a newer version.
                                        matchedFilesToRemove.Add(moduleVersion.Item1);
                                    }
                                    else
                                    {
                                        //Remove the new file as higher version item is already in dictionary.
                                        matchedFilesToRemove.Add(fileFullName);
                                    }
                                }
                            }
                            else
                            {
                                //Add the module to the dictionary as it was not processes earlier.
                                modulesAndVersion.Add(new Tuple <string, string>(moduleName, fileName),
                                                      new Tuple <string, Version>(fileFullName, moduleVersionFromPath));
                            }
                        }
                    }

                    filesProcessed.Add(fileName);
                }
            }

            return(matchedFilesToRemove);
        }
Beispiel #15
0
 internal static void ExportModuleMembers(
     PSCmdlet cmdlet,
     SessionStateInternal sessionState,
     List <WildcardPattern> functionPatterns,
     List <WildcardPattern> cmdletPatterns,
     List <WildcardPattern> aliasPatterns,
     List <WildcardPattern> variablePatterns)
 {
     sessionState.UseExportList = true;
     if (functionPatterns != null)
     {
         foreach (KeyValuePair <string, FunctionInfo> keyValuePair in (IEnumerable <KeyValuePair <string, FunctionInfo> >)sessionState.ModuleScope.FunctionTable)
         {
             if (SessionStateUtilities.MatchesAnyWildcardPattern(keyValuePair.Key, (IEnumerable <WildcardPattern>)functionPatterns, false))
             {
                 string text = ResourceManagerCache.FormatResourceString("Modules", "ExportingFunction", (object)keyValuePair.Key);
                 cmdlet.WriteVerbose(text);
                 sessionState.ExportedFunctions.Add(keyValuePair.Value);
             }
         }
         ModuleIntrinsics.SortAndRemoveDuplicates <FunctionInfo>(sessionState.ExportedFunctions, (Converter <FunctionInfo, string>)(ci => ci.Name));
     }
     if (cmdletPatterns != null)
     {
         IDictionary <string, List <CmdletInfo> > cmdletCache = (IDictionary <string, List <CmdletInfo> >)sessionState.CmdletCache;
         if (sessionState.Module.CompiledExports.Count > 0)
         {
             CmdletInfo[] array = sessionState.Module.CompiledExports.ToArray();
             sessionState.Module.CompiledExports.Clear();
             foreach (CmdletInfo cmdletInfo1 in array)
             {
                 if (SessionStateUtilities.MatchesAnyWildcardPattern(cmdletInfo1.Name, (IEnumerable <WildcardPattern>)cmdletPatterns, false))
                 {
                     string text = ResourceManagerCache.FormatResourceString("Modules", "ExportingCmdlet", (object)cmdletInfo1.Name);
                     cmdlet.WriteVerbose(text);
                     CmdletInfo cmdletInfo2 = new CmdletInfo(cmdletInfo1.Name, cmdletInfo1.ImplementingType, cmdletInfo1.HelpFile, (PSSnapInInfo)null, cmdletInfo1.Context);
                     cmdletInfo2.SetModule(sessionState.Module);
                     sessionState.Module.CompiledExports.Add(cmdletInfo2);
                 }
             }
         }
         foreach (KeyValuePair <string, List <CmdletInfo> > keyValuePair in (IEnumerable <KeyValuePair <string, List <CmdletInfo> > >)cmdletCache)
         {
             if (SessionStateUtilities.MatchesAnyWildcardPattern(keyValuePair.Key, (IEnumerable <WildcardPattern>)cmdletPatterns, false))
             {
                 string text = ResourceManagerCache.FormatResourceString("Modules", "ExportingCmdlet", (object)keyValuePair.Key);
                 cmdlet.WriteVerbose(text);
                 CmdletInfo cmdletInfo1 = keyValuePair.Value[0];
                 CmdletInfo cmdletInfo2 = new CmdletInfo(cmdletInfo1.Name, cmdletInfo1.ImplementingType, cmdletInfo1.HelpFile, (PSSnapInInfo)null, cmdletInfo1.Context);
                 cmdletInfo2.SetModule(sessionState.Module);
                 sessionState.Module.CompiledExports.Add(cmdletInfo2);
             }
         }
         ModuleIntrinsics.SortAndRemoveDuplicates <CmdletInfo>(sessionState.Module.CompiledExports, (Converter <CmdletInfo, string>)(ci => ci.Name));
     }
     if (variablePatterns != null)
     {
         foreach (KeyValuePair <string, PSVariable> variable in (IEnumerable <KeyValuePair <string, PSVariable> >)sessionState.ModuleScope.Variables)
         {
             if (!variable.Value.IsAllScope && Array.IndexOf <string>(PSModuleInfo.builtinVariables, variable.Key) == -1 && SessionStateUtilities.MatchesAnyWildcardPattern(variable.Key, (IEnumerable <WildcardPattern>)variablePatterns, false))
             {
                 string text = ResourceManagerCache.FormatResourceString("Modules", "ExportingVariable", (object)variable.Key);
                 cmdlet.WriteVerbose(text);
                 sessionState.ExportedVariables.Add(variable.Value);
             }
         }
         ModuleIntrinsics.SortAndRemoveDuplicates <PSVariable>(sessionState.ExportedVariables, (Converter <PSVariable, string>)(v => v.Name));
     }
     if (aliasPatterns == null)
     {
         return;
     }
     foreach (AliasInfo aliasInfo in sessionState.ModuleScope.AliasTable)
     {
         if ((aliasInfo.Options & ScopedItemOptions.AllScope) == ScopedItemOptions.None && SessionStateUtilities.MatchesAnyWildcardPattern(aliasInfo.Name, (IEnumerable <WildcardPattern>)aliasPatterns, false))
         {
             string text = ResourceManagerCache.FormatResourceString("Modules", "ExportingAlias", (object)aliasInfo.Name);
             cmdlet.WriteVerbose(text);
             sessionState.ExportedAliases.Add(aliasInfo);
         }
     }
     ModuleIntrinsics.SortAndRemoveDuplicates <AliasInfo>(sessionState.ExportedAliases, (Converter <AliasInfo, string>)(ci => ci.Name));
 }
Beispiel #16
0
 internal ModuleIntrinsics(ExecutionContext context)
 {
     this._context = context;
     ModuleIntrinsics.SetModulePath();
 }
Beispiel #17
0
        internal static DirectoryInfo CreateModuleDirectory(PSCmdlet cmdlet, string moduleNameOrPath, bool force)
        {
            Dbg.Assert(cmdlet != null, "Caller should verify cmdlet != null");
            Dbg.Assert(!string.IsNullOrEmpty(moduleNameOrPath), "Caller should verify !string.IsNullOrEmpty(moduleNameOrPath)");

            DirectoryInfo directoryInfo = null;

            try
            {
                // Even if 'moduleNameOrPath' is a rooted path, 'ResolveRootedFilePath' may return null when the path doesn't exist yet,
                // or when it contains wildcards but cannot be resolved to a single path.
                string rootedPath = ModuleCmdletBase.ResolveRootedFilePath(moduleNameOrPath, cmdlet.Context);
                if (string.IsNullOrEmpty(rootedPath) && moduleNameOrPath.StartsWith('.'))
                {
                    PathInfo currentPath = cmdlet.CurrentProviderLocation(cmdlet.Context.ProviderNames.FileSystem);
                    rootedPath = Path.Combine(currentPath.ProviderPath, moduleNameOrPath);
                }

                if (string.IsNullOrEmpty(rootedPath))
                {
                    if (Path.IsPathRooted(moduleNameOrPath))
                    {
                        rootedPath = moduleNameOrPath;
                    }
                    else
                    {
                        string personalModuleRoot = ModuleIntrinsics.GetPersonalModulePath();
                        if (string.IsNullOrEmpty(personalModuleRoot))
                        {
                            cmdlet.ThrowTerminatingError(
                                new ErrorRecord(
                                    new ArgumentException(StringUtil.Format(PathUtilsStrings.ExportPSSession_ErrorModuleNameOrPath, moduleNameOrPath)),
                                    "ExportPSSession_ErrorModuleNameOrPath",
                                    ErrorCategory.InvalidArgument,
                                    cmdlet));
                        }

                        rootedPath = Path.Combine(personalModuleRoot, moduleNameOrPath);
                    }
                }

                directoryInfo = new DirectoryInfo(rootedPath);
                if (directoryInfo.Exists)
                {
                    if (!force)
                    {
                        string errorMessage = string.Format(
                            CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant
                            PathUtilsStrings.ExportPSSession_ErrorDirectoryExists,
                            directoryInfo.FullName);
                        ErrorDetails details     = new ErrorDetails(errorMessage);
                        ErrorRecord  errorRecord = new ErrorRecord(
                            new ArgumentException(details.Message),
                            "ExportProxyCommand_OutputDirectoryExists",
                            ErrorCategory.ResourceExists,
                            directoryInfo);
                        cmdlet.ThrowTerminatingError(errorRecord);
                    }
                }
                else
                {
                    directoryInfo.Create();
                }
            }
            catch (Exception e)
            {
                string errorMessage = string.Format(
                    CultureInfo.InvariantCulture, // directory name should be treated as culture-invariant
                    PathUtilsStrings.ExportPSSession_CannotCreateOutputDirectory,
                    moduleNameOrPath,
                    e.Message);
                ErrorDetails details     = new ErrorDetails(errorMessage);
                ErrorRecord  errorRecord = new ErrorRecord(
                    new ArgumentException(details.Message, e),
                    "ExportProxyCommand_CannotCreateOutputDirectory",
                    ErrorCategory.ResourceExists,
                    moduleNameOrPath);
                cmdlet.ThrowTerminatingError(errorRecord);
            }

            return(directoryInfo);
        }