private void ExecuteInitScripts()
        {
            // Fix for Bug 1426 Disallow ExecuteInitScripts from being executed concurrently by multiple threads.
            lock (_initScriptsLock)
            {
                if (!_solutionManager.IsSolutionOpen)
                {
                    return;
                }

                Debug.Assert(_settings != null);
                if (_settings == null)
                {
                    return;
                }

                try
                {
                    // invoke init.ps1 files in the order of package dependency.
                    // if A -> B, we invoke B's init.ps1 before A's.
                    IEnumerable<NuGetProject> projects = _solutionManager.GetNuGetProjects();
                    NuGetPackageManager packageManager = new NuGetPackageManager(_sourceRepositoryProvider, _settings, _solutionManager);
                    List<PackageIdentity> sortedPackages = new List<PackageIdentity>();
                    foreach (NuGetProject project in projects)
                    {
                        // Skip project K projects.
                        if (project is NuGet.ProjectManagement.Projects.ProjectKNuGetProjectBase)
                        {
                            continue;
                        }

                        IEnumerable<PackageReference> installedRefs = project.GetInstalledPackagesAsync(CancellationToken.None).Result;
                        if (installedRefs != null && installedRefs.Any())
                        {
                            IEnumerable<PackageIdentity> installedPackages = packageManager.GetInstalledPackagesInDependencyOrder(project, new EmptyNuGetProjectContext(), CancellationToken.None).Result;
                            sortedPackages.AddRange(installedPackages);
                        }
                    }

                    // Get the path to the Packages folder.
                    string packagesFolderPath = packageManager.PackagesFolderSourceRepository.PackageSource.Source;
                    foreach (var package in sortedPackages)
                    {
                        PackagePathResolver packagePathResolver = new PackagePathResolver(packagesFolderPath);
                        string pathToPackage = packagePathResolver.GetInstalledPath(package);
                        string toolsPath = Path.Combine(pathToPackage, "tools");
                        AddPathToEnvironment(toolsPath);
                        Runspace.ExecuteScript(toolsPath, PowerShellScripts.Init, package);
                    }
                }
                catch (Exception ex)
                {
                    // When Packages folder is not present, NuGetResolverInputException will be thrown
                    // as resolving DependencyInfo requires the presence of Packages folder.
                    if (ex.InnerException is NuGetResolverInputException)
                    {
                        // Silently fail.
                    }
                    else
                    {
                        // if execution of Init scripts fails, do not let it crash our console
                        ReportError(ex);
                    }

                    ExceptionHelper.WriteToActivityLog(ex);
                }
            }
        }
        public async Task TestPacManGetInstalledPackagesByDependencyOrder()
        {
            // Arrange
            var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateV3OnlySourceRepositoryProvider();
            var testSolutionManager = new TestSolutionManager();
            var testSettings = new NullSettings();
            var token = CancellationToken.None;
            var nuGetPackageManager = new NuGetPackageManager(sourceRepositoryProvider, testSettings, testSolutionManager);
            var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);

            var randomPackagesConfigFolderPath = TestFilesystemUtility.CreateRandomTestFolder();
            var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");
            var testNuGetProjectContext = new TestNuGetProjectContext();

            var projectTargetFramework = NuGetFramework.Parse("net45");
            var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, testNuGetProjectContext);
            var msBuildNuGetProject = new MSBuildNuGetProject(msBuildNuGetProjectSystem, packagesFolderPath, randomPackagesConfigPath);
            var packageIdentity = PackageWithDeepDependency[6]; // WindowsAzure.Storage.4.3.0

            // Pre-Assert
            // Check that the packages.config file does not exist
            Assert.False(File.Exists(randomPackagesConfigPath));
            // Check that there are no packages returned by PackagesConfigProject
            var packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(0, packagesInPackagesConfig.Count);
            Assert.Equal(0, msBuildNuGetProjectSystem.References.Count);

            // Act
            await nuGetPackageManager.InstallPackageAsync(msBuildNuGetProject, packageIdentity,
                new ResolutionContext(), testNuGetProjectContext, sourceRepositoryProvider.GetRepositories().First(), null, token);

            // Assert
            // Check that the packages.config file exists after the installation
            Assert.True(File.Exists(randomPackagesConfigPath));
            // Check the number of packages and packages returned by PackagesConfigProject after the installation
            packagesInPackagesConfig = (await msBuildNuGetProject.PackagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
            Assert.Equal(7, packagesInPackagesConfig.Count);
            var installedPackages = PackageWithDeepDependency.OrderBy(f => f.Id).ToList();
            for (int i = 0; i < 7; i++)
            {
                Assert.True(installedPackages[i].Equals(packagesInPackagesConfig[i].PackageIdentity));
                Assert.Equal(projectTargetFramework, packagesInPackagesConfig[i].TargetFramework);
            }

            // Main Assert
            List<PackageIdentity> installedPackagesInDependencyOrder = (await nuGetPackageManager.GetInstalledPackagesInDependencyOrder
                (msBuildNuGetProject, testNuGetProjectContext, token)).ToList();
            Assert.Equal(7, installedPackagesInDependencyOrder.Count);
            for (int i = 0; i < 7; i++)
            {
                Assert.Equal(PackageWithDeepDependency[i], installedPackagesInDependencyOrder[i], PackageIdentity.Comparer);
            }

            // Clean-up
            TestFilesystemUtility.DeleteRandomTestFolders(testSolutionManager.SolutionDirectory, randomPackagesConfigFolderPath);
        }