Esempio n. 1
0
        // from reflector (system.management.automation)
        //internal static T FromObjectAs<T>(object castObject)
        //{
        //    T local = default(T);
        //    PSObject obj2 = castObject as PSObject;
        //    if (obj2 == null)
        //    {
        //        try
        //        {
        //            return (T)castObject;
        //        }
        //        catch (InvalidCastException)
        //        {
        //            return default(T);
        //        }
        //    }
        //    try
        //    {
        //        return (T)obj2.BaseObject;
        //    }
        //    catch (InvalidCastException)
        //    {
        //        return default(T);
        //    }
        //}

        private void WriteDebug(string message)
        {
            if (m_command != null)
            {
                m_command.WriteDebug(message);
            }
        }
Esempio n. 2
0
        public void Write(Verbosity verbosity, LogLevel level, string format, params object[] args)
        {
            switch (level)
            {
            case LogLevel.Error:
            case LogLevel.Fatal:
                _cmdlet.WriteWarning(string.Format(format, args));
                return;

            case LogLevel.Warning:
                _cmdlet.WriteWarning(string.Format(format, args));
                return;

            case LogLevel.Information:
                _cmdlet.WriteObject(string.Format(format, args));
                return;

            case LogLevel.Verbose:
                _cmdlet.WriteVerbose(string.Format(format, args));
                return;

            case LogLevel.Debug:
                _cmdlet.WriteDebug(string.Format(format, args));
                return;

            default:
                throw new InvalidOperationException("Invalid log level.");
            }
        }
        /// <summary>
        /// Execute the given cmdlet in powershell with the given parameters after injecting the given exception.  It is expected that the cmdlet has a runtime that can be used for receiving output
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cmdlet">The cmdlet to execute</param>
        /// <param name="name">The name of the cmdlet</param>
        /// <param name="exception">The exception to inject into the error stream</param>
        /// <param name="cmdletParameters">The parameters to pass to the cmdlet on the pipeline</param>
        public static void ExecuteCmdletWithExceptionInPipeline <T>(this PSCmdlet cmdlet, string name, Exception exception, params KeyValuePair <string, object>[] cmdletParameters)
        {
            List <T> output = new List <T>();

            using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create(RunspaceMode.NewRunspace))
            {
                var info = new CmdletInfo(name, cmdlet.GetType());
                powershell.AddCommand("Write-Error");
                powershell.AddParameter("Exception", exception);
                powershell.Invoke();
                powershell.Commands.Clear();
                powershell.AddCommand(info);
                foreach (var pair in cmdletParameters)
                {
                    if (pair.Value == null)
                    {
                        powershell.AddParameter(pair.Key);
                    }
                    else
                    {
                        powershell.AddParameter(pair.Key, pair.Value);
                    }
                }
                Collection <T> result = powershell.Invoke <T>();
                powershell.Streams.Error.ForEach(cmdlet.WriteError);
                powershell.Streams.Debug.ForEach(d => cmdlet.WriteDebug(d.Message));
                powershell.Streams.Verbose.ForEach(v => cmdlet.WriteWarning(v.Message));
                powershell.Streams.Warning.ForEach(w => cmdlet.WriteWarning(w.Message));

                if (result != null && result.Count > 0)
                {
                    result.ForEach(r => cmdlet.WriteObject(r));
                }
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Utility function used to create OrderByPropertyEntry for the supplied input object.
        /// </summary>
        /// <param name="cmdlet">PSCmdlet</param>
        /// <param name="inputObject">Input Object.</param>
        /// <param name="isCaseSensitive">Indicates if the Property value comparisons need to be case sensitive or not.</param>
        /// <param name="cultureInfo">Culture Info that needs to be used for comparison.</param>
        /// <returns>OrderByPropertyEntry for the supplied InputObject.</returns>
        internal OrderByPropertyEntry CreateOrderByPropertyEntry(
            PSCmdlet cmdlet,
            PSObject inputObject,
            bool isCaseSensitive,
            CultureInfo cultureInfo)
        {
            Diagnostics.Assert(cmdlet != null, "cmdlet must be an instance");

            if (_unExpandedParametersWithWildCardPattern != null)
            {
                ExpandExpressions(inputObject, _unExpandedParametersWithWildCardPattern, _mshParameterList);
            }

            List <ErrorRecord>   evaluationErrors     = new List <ErrorRecord>();
            List <string>        propertyNotFoundMsgs = new List <string>();
            OrderByPropertyEntry result =
                OrderByPropertyEntryEvaluationHelper.ProcessObject(inputObject, _mshParameterList, evaluationErrors, propertyNotFoundMsgs, isCaseSensitive, cultureInfo);

            foreach (ErrorRecord err in evaluationErrors)
            {
                cmdlet.WriteError(err);
            }
            foreach (string debugMsg in propertyNotFoundMsgs)
            {
                cmdlet.WriteDebug(debugMsg);
            }

            return(result);
        }
Esempio n. 5
0
        internal static List <OrderByPropertyEntry> CreateOrderMatrix(
            PSCmdlet cmdlet,
            List <PSObject> inputObjects,
            List <MshParameter> mshParameterList
            )
        {
            List <OrderByPropertyEntry> orderMatrixToCreate = new List <OrderByPropertyEntry>();

            foreach (PSObject so in inputObjects)
            {
                if (so == null || so == AutomationNull.Value)
                {
                    continue;
                }
                List <ErrorRecord>   evaluationErrors     = new List <ErrorRecord>();
                List <string>        propertyNotFoundMsgs = new List <string>();
                OrderByPropertyEntry result =
                    OrderByPropertyEntryEvaluationHelper.ProcessObject(so, mshParameterList, evaluationErrors, propertyNotFoundMsgs);
                foreach (ErrorRecord err in evaluationErrors)
                {
                    cmdlet.WriteError(err);
                }
                foreach (string debugMsg in propertyNotFoundMsgs)
                {
                    cmdlet.WriteDebug(debugMsg);
                }
                orderMatrixToCreate.Add(result);
            }

            return(orderMatrixToCreate);
        }
Esempio n. 6
0
 internal static void DebugMessage(string message)
 {
     try
     {
         _cmdlet.WriteDebug(message);
     }
     catch
     {
         // Ignore
     }
 }
Esempio n. 7
0
        internal void OnTelemetrySent(PSCmdlet pscmdlet)
        {
            AzurePSQoSEvent qos;

            if (_telemetry.TryGetValue(MetricHelper.TelemetryId, out qos))
            {
                qos.IsSuccess = (qos.Exception == null);
                _telemetry.LogEvent(MetricHelper.TelemetryId);
                _previousEndTime = DateTimeOffset.Now;
                pscmdlet.WriteDebug(qos.ToString());
            }
        }
Esempio n. 8
0
            public static void Log <T>(T message, LogTarget logTarget, PSCmdlet invokeAll, bool noFileLogging = false)
            {
                string messageStr = null;

                if (message is ErrorRecord)
                {
                    //cast to object and then to ErrorRecord as direct casting is not allowed
                    messageStr = ((ErrorRecord)(object)message).Exception.Message;
                }
                else
                {
                    messageStr = (string)(object)message;
                }
                string logEntry = string.Format("[{0}] {1}", System.DateTime.Now.ToString(datetimeFormat), messageStr);

                switch (logTarget)
                {
                case LogTarget.File:
                    if (!noFileLogging)
                    {
                        using (StreamWriter streamWriter = new StreamWriter(logFile, append: true))
                        {
                            streamWriter.WriteLine(logEntry);
                            streamWriter.Close();
                        };
                    }
                    break;

                case LogTarget.HostVerbose:
                    invokeAll.WriteVerbose(logEntry);
                    break;

                case LogTarget.HostDebug:
                    invokeAll.WriteDebug(logEntry);
                    break;

                case LogTarget.HostError:
                    if (message is ErrorRecord)
                    {
                        invokeAll.WriteError((ErrorRecord)(object)message);
                    }
                    break;

                case LogTarget.HostWarning:
                    invokeAll.WriteWarning(logEntry);
                    break;

                default:

                    break;
                }
            }
Esempio n. 9
0
        // Find all potential installation paths given a scope
        public static List <string> GetAllInstallationPaths(PSCmdlet psCmdlet, ScopeType scope)
        {
            List <string> installationPaths = new List <string>();
            var           PSVersion6        = new Version(6, 0);
            var           isCorePS          = psCmdlet.Host.Version >= PSVersion6;
            string        myDocumentsPath;
            string        programFilesPath;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                string powerShellType = isCorePS ? "PowerShell" : "WindowsPowerShell";

                myDocumentsPath  = Path.Combine(Environment.GetFolderPath(SpecialFolder.MyDocuments), powerShellType);
                programFilesPath = Path.Combine(Environment.GetFolderPath(SpecialFolder.ProgramFiles), powerShellType);
            }
            else
            {
                // paths are the same for both Linux and MacOS
                myDocumentsPath  = System.IO.Path.Combine(Environment.GetFolderPath(SpecialFolder.LocalApplicationData), "Powershell");
                programFilesPath = System.IO.Path.Combine("usr", "local", "share", "Powershell");
            }

            // The default user scope is CurrentUser
            if (scope == ScopeType.AllUsers)
            {
                installationPaths.Add(System.IO.Path.Combine(programFilesPath, "Modules"));
                installationPaths.Add(System.IO.Path.Combine(programFilesPath, "Scripts"));
            }
            else
            {
                installationPaths.Add(System.IO.Path.Combine(myDocumentsPath, "Modules"));
                installationPaths.Add(System.IO.Path.Combine(myDocumentsPath, "Scripts"));
            }

            installationPaths = installationPaths.Distinct(StringComparer.InvariantCultureIgnoreCase).ToList();
            installationPaths.ForEach(dir => psCmdlet.WriteDebug(string.Format("All paths to search: '{0}'", dir)));

            return(installationPaths);
        }
Esempio n. 10
0
        internal static List <OrderByPropertyEntry> CreateOrderMatrix(PSCmdlet cmdlet, List <PSObject> inputObjects, List <MshParameter> mshParameterList)
        {
            List <OrderByPropertyEntry> list = new List <OrderByPropertyEntry>();

            foreach (PSObject obj2 in inputObjects)
            {
                if ((obj2 != null) && (obj2 != AutomationNull.Value))
                {
                    List <ErrorRecord>   errors = new List <ErrorRecord>();
                    List <string>        propertyNotFoundMsgs = new List <string>();
                    OrderByPropertyEntry item = OrderByPropertyEntryEvaluationHelper.ProcessObject(obj2, mshParameterList, errors, propertyNotFoundMsgs);
                    foreach (ErrorRecord record in errors)
                    {
                        cmdlet.WriteError(record);
                    }
                    foreach (string str in propertyNotFoundMsgs)
                    {
                        cmdlet.WriteDebug(str);
                    }
                    list.Add(item);
                }
            }
            return(list);
        }
Esempio n. 11
0
        public List <PSObject> ProcessGetParams(string[] name, string version, bool prerelease, string path)
        {
            var dirsToSearch = new List <string>();

            if (path != null)
            {
                cmdletPassedIn.WriteDebug(string.Format("Provided path is: '{0}'", path));
                dirsToSearch.AddRange(Directory.GetDirectories(path).ToList());
            }
            else
            {
                // PSModules path
                var psModulePath = Environment.GetEnvironmentVariable("PSModulePath");
                var modulePaths  = psModulePath.Split(';');


#if NET472
                programFilesPath = System.IO.Path.Combine(Environment.GetFolderPath(SpecialFolder.ProgramFiles), "WindowsPowerShell");
                myDocumentsPath  = System.IO.Path.Combine(Environment.GetFolderPath(SpecialFolder.MyDocuments), "WindowsPowerShell");
#else
                // If PS6+ on Windows
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    myDocumentsPath  = System.IO.Path.Combine(Environment.GetFolderPath(SpecialFolder.MyDocuments), "PowerShell");
                    programFilesPath = System.IO.Path.Combine(Environment.GetFolderPath(SpecialFolder.ProgramFiles), "PowerShell");
                }
                else
                {
                    // Paths are the same for both Linux and MacOS
                    myDocumentsPath  = System.IO.Path.Combine(Environment.GetFolderPath(SpecialFolder.LocalApplicationData), "powershell");
                    programFilesPath = System.IO.Path.Combine("/usr", "local", "share", "powershell");
                }
#endif
                cmdletPassedIn.WriteDebug(string.Format("Current user scope path: '{0}'", myDocumentsPath));
                cmdletPassedIn.WriteDebug(string.Format("All users scope path: '{0}'", programFilesPath));

                /*** Will search first in PSModulePath, then will search in default paths ***/

                foreach (var modulePath in modulePaths)
                {
                    dirsToSearch.AddRange(Directory.GetDirectories(modulePath).ToList());
                }


                var pfModulesPath = System.IO.Path.Combine(programFilesPath, "Modules");
                if (Directory.Exists(pfModulesPath))
                {
                    dirsToSearch.AddRange(Directory.GetDirectories(pfModulesPath).ToList());
                }

                var mdModulesPath = System.IO.Path.Combine(myDocumentsPath, "Modules");
                if (Directory.Exists(mdModulesPath))
                {
                    dirsToSearch.AddRange(Directory.GetDirectories(mdModulesPath).ToList());
                }


                var pfScriptsPath = System.IO.Path.Combine(programFilesPath, "Scripts", "InstalledScriptInfos");
                if (Directory.Exists(pfScriptsPath))
                {
                    dirsToSearch.AddRange(Directory.GetFiles(pfScriptsPath).ToList());
                }

                var mdScriptsPath = System.IO.Path.Combine(myDocumentsPath, "Scripts", "InstalledScriptInfos");
                if (Directory.Exists(mdScriptsPath))
                {
                    dirsToSearch.AddRange(Directory.GetFiles(mdScriptsPath).ToList());
                }


                // uniqueify
                dirsToSearch = dirsToSearch.Distinct().ToList();
            }

            foreach (var dir in dirsToSearch)
            {
                cmdletPassedIn.WriteDebug(string.Format("All directories to search: '{0}'", dir));
            }

            // Or a list of the passed in names
            if (name != null && !name[0].Equals("*"))
            {
                var nameLowerCased = new List <string>();
                var scriptXMLnames = new List <string>();
                Array.ForEach(name, n => nameLowerCased.Add(n.ToLower()));
                Array.ForEach(name, n => scriptXMLnames.Add((n + "_InstalledScriptInfo.xml").ToLower()));

                dirsToSearch = dirsToSearch.FindAll(p => (nameLowerCased.Contains(new DirectoryInfo(p).Name.ToLower()) ||
                                                          scriptXMLnames.Contains((System.IO.Path.GetFileName(p)).ToLower())));

                cmdletPassedIn.WriteDebug(dirsToSearch.Any().ToString());
            }

            // try to parse into a specific NuGet version
            VersionRange versionRange = null;
            if (version != null)
            {
                NuGetVersion specificVersion;
                NuGetVersion.TryParse(version, out specificVersion);

                if (specificVersion != null)
                {
                    // exact version
                    versionRange = new VersionRange(specificVersion, true, specificVersion, true, null, null);
                    cmdletPassedIn.WriteDebug(string.Format("A specific version, '{0}', is specified", versionRange.ToString()));
                }
                else
                {
                    // check if version range
                    versionRange = VersionRange.Parse(version);
                    cmdletPassedIn.WriteDebug(string.Format("A version range, '{0}', is specified", versionRange.ToString()));
                }
            }

            List <string> installedPkgsToReturn = new List <string>();

            IEnumerable <string> returnPkgs = null;

            //2) use above list to check
            // if the version specificed is a version range
            if (versionRange != null)
            {
                foreach (var pkgPath in dirsToSearch)
                {
                    cmdletPassedIn.WriteDebug(string.Format("Searching through package path: '{0}'", pkgPath));
                    var versionsDirs = Directory.GetDirectories(pkgPath);

                    foreach (var versionPath in versionsDirs)
                    {
                        cmdletPassedIn.WriteDebug(string.Format("Searching through package version path: '{0}'", versionPath));
                        NuGetVersion dirAsNugetVersion;
                        var          dirInfo = new DirectoryInfo(versionPath);
                        NuGetVersion.TryParse(dirInfo.Name, out dirAsNugetVersion);
                        cmdletPassedIn.WriteDebug(string.Format("Directory parsed as NuGet version: '{0}'", dirAsNugetVersion));

                        if (versionRange.Satisfies(dirAsNugetVersion))
                        {
                            // just search scripts paths
                            if (pkgPath.ToLower().Contains("Scripts"))
                            {
                                if (File.Exists(pkgPath))
                                {
                                    installedPkgsToReturn.Add(pkgPath);
                                }
                            }
                            else
                            {
                                // modules paths
                                versionsDirs = Directory.GetDirectories(pkgPath);
                                cmdletPassedIn.WriteDebug(string.Format("Getting sub directories from : '{0}'", pkgPath));

                                // Check if the pkg path actually has version sub directories.
                                if (versionsDirs.Length != 0)
                                {
                                    Array.Sort(versionsDirs, StringComparer.OrdinalIgnoreCase);
                                    Array.Reverse(versionsDirs);

                                    var pkgXmlFilePath = System.IO.Path.Combine(versionsDirs.First(), "PSGetModuleInfo.xml");

                                    // TODO:  check if this xml file exists, if it doesn't check if it exists in a previous version
                                    cmdletPassedIn.WriteDebug(string.Format("Found module XML: '{0}'", pkgXmlFilePath));

                                    installedPkgsToReturn.Add(pkgXmlFilePath);
                                }
                            }

                            installedPkgsToReturn.Add(versionPath);
                        }
                    }
                }
            }
            else
            {
                cmdletPassedIn.WriteDebug("No version provided-- check each path for the requested package");
                // if no version is specified, just get the latest version
                foreach (var pkgPath in dirsToSearch)
                {
                    cmdletPassedIn.WriteDebug(string.Format("Searching through package path: '{0}'", pkgPath));

                    // just search scripts paths
                    if (pkgPath.ToLower().Contains("scripts"))
                    {
                        if (File.Exists(pkgPath))   //check to make sure properly formatted
                        {
                            installedPkgsToReturn.Add(pkgPath);
                        }
                    }
                    else
                    {
                        // modules paths
                        string[] versionsDirs = new string[0];

                        versionsDirs = Directory.GetDirectories(pkgPath);

                        // Check if the pkg path actually has version sub directories.
                        if (versionsDirs.Length != 0)
                        {
                            Array.Sort(versionsDirs, StringComparer.OrdinalIgnoreCase);
                            Array.Reverse(versionsDirs);

                            var pkgXmlFilePath = System.IO.Path.Combine(versionsDirs.First(), "PSGetModuleInfo.xml");

                            // TODO:  check if this xml file exists, if it doesn't check if it exists in a previous version
                            cmdletPassedIn.WriteDebug(string.Format("Found package XML: '{0}'", pkgXmlFilePath));
                            installedPkgsToReturn.Add(pkgXmlFilePath);
                        }
                    }
                }
            }


            // Flatten returned pkgs before displaying output returnedPkgsFound.Flatten().ToList()[0]
            var flattenedPkgs = installedPkgsToReturn.Flatten();



            List <PSObject> foundInstalledPkgs = new List <PSObject>();

            foreach (string xmlFilePath in flattenedPkgs)
            {
                cmdletPassedIn.WriteDebug(string.Format("Reading package metadata from: '{0}'", xmlFilePath));

                // Open xml and read metadata from it
                if (File.Exists(xmlFilePath))
                {
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> nameInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> versionInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> typeInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> descriptionInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> authorInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> companyNameInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> copyrightInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> publishedDateInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> installedDateInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> updatedDateInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> licenseUriInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> projectUriInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> iconUriInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> tagsInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> includesInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> powerShellGetFormatVersionInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> releaseNotesInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> dependenciesInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> repositorySourceLocationInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> repositoryInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> additionalMetadataInfo;
                    ReadOnlyPSMemberInfoCollection <PSPropertyInfo> installedLocationInfo;


                    //var isPrelease = false;
                    using (StreamReader sr = new StreamReader(xmlFilePath))
                    {
                        string text            = sr.ReadToEnd();
                        var    deserializedObj = (PSObject)PSSerializer.Deserialize(text);

                        nameInfo          = deserializedObj.Properties.Match("Name");
                        versionInfo       = deserializedObj.Properties.Match("Version");
                        typeInfo          = deserializedObj.Properties.Match("Type");
                        descriptionInfo   = deserializedObj.Properties.Match("Description");
                        authorInfo        = deserializedObj.Properties.Match("Author");
                        companyNameInfo   = deserializedObj.Properties.Match("CompanyName");
                        copyrightInfo     = deserializedObj.Properties.Match("Copyright");
                        publishedDateInfo = deserializedObj.Properties.Match("PublishedDate");
                        installedDateInfo = deserializedObj.Properties.Match("InstalledDate");
                        updatedDateInfo   = deserializedObj.Properties.Match("UpdatedDate");
                        licenseUriInfo    = deserializedObj.Properties.Match("LicenseUri");
                        projectUriInfo    = deserializedObj.Properties.Match("ProjectUri");
                        iconUriInfo       = deserializedObj.Properties.Match("IconUri");
                        tagsInfo          = deserializedObj.Properties.Match("Tags");
                        includesInfo      = deserializedObj.Properties.Match("Includes");
                        powerShellGetFormatVersionInfo = deserializedObj.Properties.Match("PowerShellGetFormatVersion");
                        releaseNotesInfo             = deserializedObj.Properties.Match("ReleaseNotes");
                        dependenciesInfo             = deserializedObj.Properties.Match("Dependencies");
                        repositorySourceLocationInfo = deserializedObj.Properties.Match("RepositorySourceLocation");
                        repositoryInfo         = deserializedObj.Properties.Match("Repository");
                        additionalMetadataInfo = deserializedObj.Properties.Match("AdditionalMetadata");
                        installedLocationInfo  = deserializedObj.Properties.Match("InstalledLocation");


                        /* // testing adding prerelease parameter
                         * additionalMetadataInfo = deserializedObj.Properties.Match("AdditionalMetadata");
                         * if (additionalMetadataInfo.Any())
                         * {
                         *  isPrelease = additionalMetadataInfo.FirstOrDefault().Value.ToString().Contains("IsPrerelease=true");
                         *  if ((isPrelease == true) && _prerelease) // find a stable version of the pkg {}
                         * }
                         */
                    };

                    // if -Prerelease is not passed in as a parameter, don't allow prerelease pkgs to be returned,
                    // we still want all pkgs to be returned if -Prerelease is passed in as a param
                    //if ((_prerelease == false && isPrelease == false) || _prerelease == true)
                    //{

                    //var foundPkgs = List<PSObject>();

                    PSObject pkgAsPSObject = new PSObject();
                    try
                    {
                        pkgAsPSObject.Members.Add(new PSNoteProperty("Name", nameInfo.Any()? nameInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("Version", versionInfo.Any()? versionInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("Type", typeInfo.Any()? typeInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("Description", descriptionInfo.Any()? descriptionInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("Author", authorInfo.Any()? authorInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("CompanyName", companyNameInfo.Any()? companyNameInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("Copyright", copyrightInfo.Any()? copyrightInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("PublishedDate", publishedDateInfo.Any()? publishedDateInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("InstalledDate", installedDateInfo.Any()? installedDateInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("UpdatedDate", updatedDateInfo.Any()? updatedDateInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("LicenseUri", licenseUriInfo.Any()? licenseUriInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("ProjectUri", projectUriInfo.Any()? projectUriInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("IconUri", iconUriInfo.Any()? iconUriInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("Tags", tagsInfo.Any()? tagsInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("Includes", includesInfo.Any()? includesInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("PowerShellGetFormatVersion", powerShellGetFormatVersionInfo.Any()? powerShellGetFormatVersionInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("ReleaseNotes", releaseNotesInfo.Any()? releaseNotesInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("Dependencies", dependenciesInfo.Any()? dependenciesInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("RepositorySourceLocation", repositorySourceLocationInfo.Any()? repositorySourceLocationInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("Repository", repositoryInfo.Any()? repositoryInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("AdditionalMetadata", additionalMetadataInfo.Any()? additionalMetadataInfo.FirstOrDefault().Value : string.Empty));
                        pkgAsPSObject.Members.Add(new PSNoteProperty("InstalledLocation", installedLocationInfo.Any()? installedLocationInfo.FirstOrDefault().Value : string.Empty));


                        // verify that this works, then add the object to a list and return it
                        //WriteObject(pkgAsPSObject);
                        foundInstalledPkgs.Add(pkgAsPSObject);
                    }
                    catch { }
                }
            }

            // return here
            return(foundInstalledPkgs);
        }
Esempio n. 12
0
        private void LogDebug(string format, params object[] parameters)
        {
            var message = String.Format(format, parameters);

            cmdlet.WriteDebug(message);
        }
 internal static void DebugMessage(string message)
 {
     _cmdlet.WriteDebug(message);
 }
Esempio n. 14
0
        public void InstallPackages(
            string[] names,
            VersionRange versionRange,
            bool prerelease,
            string[] repository,
            bool acceptLicense,
            bool quiet,
            bool reinstall,
            bool force,
            bool trustRepository,
            bool noClobber,
            PSCredential credential,
            string requiredResourceFile,
            string requiredResourceJson,
            Hashtable requiredResourceHash,
            string specifiedPath,
            bool asNupkg,
            bool includeXML,
            List <string> pathsToInstallPkg)
        {
            _cmdletPassedIn.WriteDebug(string.Format("Parameters passed in >>> Name: '{0}'; Version: '{1}'; Prerelease: '{2}'; Repository: '{3}'; " +
                                                     "AcceptLicense: '{4}'; Quiet: '{5}'; Reinstall: '{6}'; TrustRepository: '{7}'; NoClobber: '{8}';",
                                                     string.Join(",", names),
                                                     (_versionRange != null ? _versionRange.OriginalString : string.Empty),
                                                     prerelease.ToString(),
                                                     repository != null ? string.Join(",", repository) : string.Empty,
                                                     acceptLicense.ToString(),
                                                     quiet.ToString(),
                                                     reinstall.ToString(),
                                                     trustRepository.ToString(),
                                                     noClobber.ToString()));

            _versionRange      = versionRange;
            _prerelease        = prerelease;
            _acceptLicense     = acceptLicense;
            _quiet             = quiet;
            _reinstall         = reinstall;
            _force             = force;
            _trustRepository   = trustRepository;
            _noClobber         = noClobber;
            _credential        = credential;
            _specifiedPath     = specifiedPath;
            _asNupkg           = asNupkg;
            _includeXML        = includeXML;
            _pathsToInstallPkg = pathsToInstallPkg;

            // Go through the repositories and see which is the first repository to have the pkg version available
            ProcessRepositories(names, repository, _trustRepository, _credential);
        }
Esempio n. 15
0
        public Dictionary <string, List <string> > CheckRuleExtension(string[] path, PSCmdlet cmdlet)
        {
            Dictionary <string, List <string> > results = new Dictionary <string, List <string> >();

            List <string> invalidPaths  = new List <string>();
            List <string> validDllPaths = new List <string>();
            List <string> validModPaths = new List <string>();

            // Gets valid module names
            foreach (string childPath in path)
            {
                try
                {
                    cmdlet.WriteVerbose(string.Format(CultureInfo.CurrentCulture, Strings.CheckModuleName, childPath));

                    string resolvedPath = string.Empty;

                    // Users may provide a valid module path or name,
                    // We have to identify the childPath is really a directory or just a module name.
                    // You can also consider following two commands.
                    //   Get-ScriptAnalyzerRule -RuleExtension "ContosoAnalyzerRules"
                    //   Get-ScriptAnalyzerRule -RuleExtension "%USERPROFILE%\WindowsPowerShell\Modules\ContosoAnalyzerRules"
                    if (Path.GetDirectoryName(childPath) == string.Empty)
                    {
                        resolvedPath = childPath;
                    }
                    else
                    {
                        resolvedPath = cmdlet.SessionState.Path
                                       .GetResolvedPSPathFromPSPath(childPath).First().ToString();
                    }

                    using (System.Management.Automation.PowerShell posh =
                               System.Management.Automation.PowerShell.Create())
                    {
                        string       script     = string.Format(CultureInfo.CurrentCulture, "Get-Module -Name '{0}' -ListAvailable", resolvedPath);
                        PSModuleInfo moduleInfo = posh.AddScript(script).Invoke <PSModuleInfo>().First();

                        // Adds original path, otherwise path.Except<string>(validModPaths) will fail.
                        // It's possible that user can provide something like this:
                        // "..\..\..\ScriptAnalyzer.UnitTest\modules\CommunityAnalyzerRules\CommunityAnalyzerRules.psd1"
                        if (moduleInfo.ExportedFunctions.Count > 0)
                        {
                            validModPaths.Add(childPath);
                        }
                    }
                }
                catch
                {
                    // User may provide an invalid module name, like c:\temp.
                    // It's a invalid name for a Windows PowerShell module,
                    // But we need test it further since we allow user to provide a folder to extend rules.
                    // You can also consider following two commands.
                    //   Get-ScriptAnalyzerRule -RuleExtension "ContosoAnalyzerRules", "C:\Temp\ExtendScriptAnalyzerRules.dll"
                    //   Get-ScriptAnalyzerRule -RuleExtension "ContosoAnalyzerRules", "C:\Temp\"
                    continue;
                }
            }

            // Gets valid dll paths
            foreach (string childPath in path.Except <string>(validModPaths))
            {
                try
                {
                    string resolvedPath = cmdlet.SessionState.Path
                                          .GetResolvedPSPathFromPSPath(childPath).First().ToString();

                    cmdlet.WriteDebug(string.Format(CultureInfo.CurrentCulture, Strings.CheckAssemblyFile, resolvedPath));

                    if (String.Equals(Path.GetExtension(resolvedPath), ".dll", StringComparison.OrdinalIgnoreCase))
                    {
                        if (!File.Exists(resolvedPath))
                        {
                            invalidPaths.Add(resolvedPath);
                            continue;
                        }
                    }
                    else
                    {
                        if (!Directory.Exists(resolvedPath))
                        {
                            invalidPaths.Add(resolvedPath);
                            continue;
                        }
                    }

                    validDllPaths.Add(resolvedPath);
                }
                catch
                {
                    invalidPaths.Add(childPath);
                }
            }

            // Resloves relative paths.
            try
            {
                for (int i = 0; i < validModPaths.Count; i++)
                {
                    validModPaths[i] = cmdlet.SessionState.Path
                                       .GetResolvedPSPathFromPSPath(validModPaths[i]).First().ToString();
                }
                for (int i = 0; i < validDllPaths.Count; i++)
                {
                    validDllPaths[i] = cmdlet.SessionState.Path
                                       .GetResolvedPSPathFromPSPath(validDllPaths[i]).First().ToString();
                }
            }
            catch
            {
                // If GetResolvedPSPathFromPSPath failed. We can safely ignore the exception.
                // Because GetResolvedPSPathFromPSPath always fails when trying to resolve a module name.
            }

            // Returns valid rule extensions
            results.Add("InvalidPaths", invalidPaths);
            results.Add("ValidModPaths", validModPaths);
            results.Add("ValidDllPaths", validDllPaths);

            return(results);
        }
Esempio n. 16
0
 public void WriteDebug(string text)
 {
     _cmd?.WriteDebug(text);
 }
Esempio n. 17
0
        public static List <string> GetAllResourcePaths(PSCmdlet psCmdlet)
        {
            string        psModulePath  = Environment.GetEnvironmentVariable("PSModulePath");
            List <string> resourcePaths = psModulePath.Split(';').ToList();
            List <string> pathsToSearch = new List <string>();
            var           PSVersion6    = new Version(6, 0);
            var           isCorePS      = psCmdlet.Host.Version >= PSVersion6;
            string        myDocumentsPath;
            string        programFilesPath;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                string powerShellType = isCorePS ? "PowerShell" : "WindowsPowerShell";

                myDocumentsPath  = Path.Combine(Environment.GetFolderPath(SpecialFolder.MyDocuments), powerShellType);
                programFilesPath = Path.Combine(Environment.GetFolderPath(SpecialFolder.ProgramFiles), powerShellType);
            }
            else
            {
                // paths are the same for both Linux and MacOS
                myDocumentsPath  = System.IO.Path.Combine(Environment.GetFolderPath(SpecialFolder.LocalApplicationData), "Powershell");
                programFilesPath = System.IO.Path.Combine("usr", "local", "share", "Powershell");
            }

            // will search first in PSModulePath, then will search in default paths
            resourcePaths.Add(System.IO.Path.Combine(myDocumentsPath, "Modules"));
            resourcePaths.Add(System.IO.Path.Combine(programFilesPath, "Modules"));
            resourcePaths.Add(System.IO.Path.Combine(myDocumentsPath, "Scripts"));
            resourcePaths.Add(System.IO.Path.Combine(programFilesPath, "Scripts"));

            // resourcePaths should now contain, eg:
            // ./PowerShell/Scripts
            // ./PowerShell/Modules
            // add all module directories or script files
            foreach (string path in resourcePaths)
            {
                psCmdlet.WriteDebug(string.Format("Retrieving directories in the path '{0}'", path));

                if (path.EndsWith("Scripts"))
                {
                    try
                    {
                        pathsToSearch.AddRange(GetDirectoryFiles(path));
                    }
                    catch (Exception e)
                    {
                        psCmdlet.WriteVerbose(string.Format("Error retrieving files from '{0}': '{1}'", path, e.Message));
                    }
                }
                else
                {
                    try
                    {
                        pathsToSearch.AddRange(GetSubDirectories(path));
                    }
                    catch (Exception e)
                    {
                        psCmdlet.WriteVerbose(string.Format("Error retrieving directories from '{0}': '{1}'", path, e.Message));
                    }
                }
            }

            // resourcePaths should now contain eg:
            // ./PowerShell/Scripts/Test-Script.ps1
            // ./PowerShell/Modules/TestModule
            // need to use .ToList() to cast the IEnumerable<string> to type List<string>
            pathsToSearch = pathsToSearch.Distinct(StringComparer.InvariantCultureIgnoreCase).ToList();
            pathsToSearch.ForEach(dir => psCmdlet.WriteDebug(string.Format("All paths to search: '{0}'", dir)));

            return(pathsToSearch);
        }
Esempio n. 18
0
        public IEnumerable <PSResourceInfo> FindByResourceName(
            string[] name,
            ResourceType type,
            string version,
            SwitchParameter prerelease,
            string[] tag,
            string[] repository,
            PSCredential credential,
            SwitchParameter includeDependencies)
        {
            _type                = type;
            _version             = version;
            _prerelease          = prerelease;
            _tag                 = tag;
            _credential          = credential;
            _includeDependencies = includeDependencies;

            Dbg.Assert(name.Length != 0, "Name length cannot be 0");

            _pkgsLeftToFind = name.ToList();

            List <PSRepositoryInfo> repositoriesToSearch;

            try
            {
                repositoriesToSearch = RepositorySettings.Read(repository, out string[] errorList);

                foreach (string error in errorList)
                {
                    _cmdletPassedIn.WriteError(new ErrorRecord(
                                                   new PSInvalidOperationException(error),
                                                   "ErrorGettingSpecifiedRepo",
                                                   ErrorCategory.InvalidOperation,
                                                   this));
                }
            }
            catch (Exception e)
            {
                _cmdletPassedIn.ThrowTerminatingError(new ErrorRecord(
                                                          new PSInvalidOperationException(e.Message),
                                                          "ErrorLoadingRepositoryStoreFile",
                                                          ErrorCategory.InvalidArgument,
                                                          this));
                yield break;
            }

            // loop through repositoriesToSearch and if PSGallery add it to list with same priority as PSGallery repo
            for (int i = 0; i < repositoriesToSearch.Count; i++)
            {
                if (String.Equals(repositoriesToSearch[i].Name, _psGalleryRepoName, StringComparison.InvariantCultureIgnoreCase))
                {
                    // for PowerShellGallery, Module and Script resources have different endpoints so separate repositories have to be registered
                    // with those endpoints in order for the NuGet APIs to search across both in the case where name includes '*'

                    // detect if Script repository needs to be added and/or Module repository needs to be skipped
                    Uri psGalleryScriptsUrl           = new Uri("http://www.powershellgallery.com/api/v2/items/psscript/");
                    PSRepositoryInfo psGalleryScripts = new PSRepositoryInfo(_psGalleryScriptsRepoName, psGalleryScriptsUrl, repositoriesToSearch[i].Priority, false);
                    if (_type == ResourceType.None)
                    {
                        _cmdletPassedIn.WriteDebug("Null Type provided, so add PSGalleryScripts repository");
                        repositoriesToSearch.Insert(i + 1, psGalleryScripts);
                    }
                    else if (_type != ResourceType.None && _type == ResourceType.Script)
                    {
                        _cmdletPassedIn.WriteDebug("Type Script provided, so add PSGalleryScripts and remove PSGallery (Modules only)");
                        repositoriesToSearch.Insert(i + 1, psGalleryScripts);
                        repositoriesToSearch.RemoveAt(i); // remove PSGallery
                    }
                }
            }

            for (int i = 0; i < repositoriesToSearch.Count && _pkgsLeftToFind.Any(); i++)
            {
                _cmdletPassedIn.WriteDebug(string.Format("Searching in repository {0}", repositoriesToSearch[i].Name));
                foreach (var pkg in SearchFromRepository(
                             repositoryName: repositoriesToSearch[i].Name,
                             repositoryUrl: repositoriesToSearch[i].Url))
                {
                    yield return(pkg);
                }
            }
        }
Esempio n. 19
0
        // Filter by user provided version
        public IEnumerable <String> FilterPkgPathsByVersion(VersionRange versionRange, List <string> dirsToSearch)
        {
            Dbg.Assert(versionRange != null, "Version Range cannot be null");

            // if no version is specified, just get the latest version
            foreach (string pkgPath in dirsToSearch)
            {
                _cmdletPassedIn.WriteDebug(string.Format("Searching through package path: '{0}'", pkgPath));

                // if this is a module directory
                if (Directory.Exists(pkgPath))
                {
                    // search modules paths
                    // ./Modules/Test-Module/1.0.0
                    // ./Modules/Test-Module/2.0.0
                    _cmdletPassedIn.WriteDebug(string.Format("Searching through package path: '{0}'", pkgPath));

                    string[] versionsDirs = Utils.GetSubDirectories(pkgPath);

                    if (versionsDirs.Length == 0)
                    {
                        _cmdletPassedIn.WriteVerbose(
                            $"No version subdirectories found for path: {pkgPath}");
                        continue;
                    }

                    // sort and reverse to get package versions in descending order to maintain consistency with V2
                    Array.Sort(versionsDirs);
                    Array.Reverse(versionsDirs);

                    foreach (string versionPath in versionsDirs)
                    {
                        _cmdletPassedIn.WriteDebug(string.Format("Searching through package version path: '{0}'", versionPath));
                        DirectoryInfo dirInfo = new DirectoryInfo(versionPath);

                        // if the version is not valid, we'll just skip it and output a debug message
                        if (!NuGetVersion.TryParse(dirInfo.Name, out NuGetVersion dirAsNugetVersion))
                        {
                            _cmdletPassedIn.WriteVerbose(string.Format("Leaf directory in path '{0}' cannot be parsed into a version.", versionPath));

                            // skip to next iteration of the loop
                            continue;
                        }
                        _cmdletPassedIn.WriteVerbose(string.Format("Directory parsed as NuGet version: '{0}'", dirAsNugetVersion));

                        if (versionRange.Satisfies(dirAsNugetVersion))
                        {
                            // This will be one version or a version range.
                            // yield results then continue with this iteration of the loop
                            yield return(versionPath);
                        }
                    }
                }
                else if (File.Exists(pkgPath))
                {
                    // if it's a script
                    if (versionRange == null || versionRange == VersionRange.All)
                    {
                        // yield results then continue with this iteration of the loop
                        yield return(pkgPath);

                        // We are now done with the current iteration of the for loop because
                        // only one script version can be installed in a particular script path at a time.
                        // if looking for all versions and one was found, then we have found all possible versions at that ./Scripts path
                        // and do not need to parse and check for the version number in the metadata file.
                    }
                    else
                    {
                        // check to make sure it's within the version range.
                        // script versions will be parsed from the script xml file
                        PSResourceInfo scriptInfo = OutputPackageObject(pkgPath, _scriptDictionary);
                        if (scriptInfo == null)
                        {
                            // if script was not found skip to the next iteration of the loop
                            continue;
                        }

                        if (!NuGetVersion.TryParse(scriptInfo.Version.ToString(), out NuGetVersion scriptVersion))
                        {
                            _cmdletPassedIn.WriteVerbose(string.Format("Version '{0}' could not be properly parsed from the script metadata file from the script installed at '{1}'", scriptInfo.Version.ToString(), scriptInfo.InstalledLocation));
                        }
                        else if (versionRange.Satisfies(scriptVersion))
                        {
                            _scriptDictionary.Add(pkgPath, scriptInfo);
                            yield return(pkgPath);
                        }
                    }
                }
            }
        }