/// <summary>
        /// Import and get the information of a Powershell module
        /// </summary>
        /// <param name="cmdlet"></param>
        /// <param name="filename"></param>
        /// <param name="moduleName">Optionally provide a module name in the very unlikely case when it cannot be set from the filename</param>
        /// <returns></returns>
        public static PSModuleInfo ImportModule(this PSCmdlet cmdlet, string filename, string moduleName = null)
        {
            var mf = cmdlet.ResolvePath(filename);

            if (!File.Exists(mf))
            {
                throw new FileNotFoundException($"Module file {mf} was not found.");
            }

            moduleName ??= Path.GetFileNameWithoutExtension(mf);
            var currdir = cmdlet.SessionState.Path.CurrentFileSystemLocation.Path;

            cmdlet.Run($"Set-Location {Path.GetDirectoryName(mf)}");
            cmdlet.Run($"Import-Module {mf}");

            PSModuleInfo res = null;

            foreach (var psObject in cmdlet.Run($"Get-Module {moduleName}"))
            {
                res = psObject.BaseObject as PSModuleInfo;
            }

            cmdlet.Run($"Set-Location {currdir}");

            if (res != null)
            {
                return(res);
            }
            throw new ItemNotFoundException($"Get-Module operation for {moduleName} yielded no results.");
        }
Пример #2
0
 public static string TryResolvePath(this PSCmdlet psCmdlet, string path)
 {
     try
     {
         return(psCmdlet.ResolvePath(path));
     }
     catch
     {
         return(path);
     }
 }