Search code examples
visual-studiopowershellvisual-studio-2012nugetproject-template

Execute PowerShell script from custom project template


I am currently creating a project template and I was wondering if it would be possible to execute a PowerShell script after the project has been created (similar to the install.ps1 in NuGet packages).

Any chance to do this without implementing my own IWizard?


Solution

  • OK... I have tried many things, but finally I ended up with the custom IWizard.

    public class InitScriptWizard : IWizard
    {
        public void RunStarted(
            object automationObject,
            Dictionary<string, string> replacementsDictionary,
            WizardRunKind runKind,
            object[] customParams)
        { }
    
        public void ProjectFinishedGenerating(Project project)
        {
            var script =
                project.ProjectItems.FindProjectItem(
                    item => item.Name.Equals("init.ps1"));
    
            if (script == null)
            {
                return;
            }
    
            var process =
                System.Diagnostics.Process.Start(
                    "powershell",
                    string.Concat(
                        "-NoProfile -ExecutionPolicy Unrestricted -File \"",
                        script.FileNames[0],
                        "\""));
    
            //if (process != null)
            //{
            //    process.WaitForExit();
            //}
    
            //script.Delete();
        }
    
        public void ProjectItemFinishedGenerating(ProjectItem projectItem)
        { }
    
        public bool ShouldAddProjectItem(string filePath)
        {
            return true;
        }
    
        public void BeforeOpeningFile(ProjectItem projectItem)
        { }
    
        public void RunFinished()
        { }
    }