├── .editorconfig ├── .github └── FUNDING.yml ├── .gitignore ├── AutoUpdateProjectsMinimumRequiredClickOnceVersion.sln ├── License.md ├── ReadMe.md ├── docs └── Images │ ├── AddScriptAndPostBuildEventToNetCoreProject.png │ ├── FileAddedToProject.png │ ├── InstallPackageWindow.png │ ├── NavigateToManageNugetPackages.png │ ├── SetNetCorePublishWizardClickOnceSettings.png │ └── SetProjectsClickOnceSettings.png ├── src ├── AutoUpdateProjectsMinimumRequiredClickOnceVersion.ps1 └── ChangesVisualStudioMakesToProjectFileThatNeedToBeMimicked │ ├── 1 - TestProject - Before turning on automatic updates and enforce min version.csproj │ ├── 2 - TestProject - After turning on min version.csproj │ ├── 3 - TestProject - After turning on automatic updates and enforce min version.csproj │ └── 4 - TestProject - Already on the latest version.csproj └── tools └── PublishNewNuGetPackage ├── AutoUpdateProjectsMinimumRequiredClickOnceVersion.nuspec ├── New-NuGetPackage.ps1 └── tools ├── Install.ps1 └── Uninstall.ps1 /.editorconfig: -------------------------------------------------------------------------------- 1 | # This file should only include settings that affect the physical contents of the file, not just how it appears in an editor. 2 | # Do not include personal preference meta-data settings like a tab's `indent_size` in this file; those should be specified in a parent .editorconfig file oustide of the repository. 3 | # v1.0 4 | 5 | # Ensure that personal preference meta-settings can be inherited from parent .editorconfig files. 6 | root = false 7 | 8 | [*] 9 | indent_style = tab 10 | end_of_line = crlf 11 | trim_trailing_whitespace = true 12 | 13 | [*.{md,psd1,yml,yaml}] 14 | indent_style = space 15 | indent_size = 2 -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: deadlydog # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: https://www.paypal.me/deadlydogDan # Replace with a single custom sponsorship URL 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.bak 2 | *.cache 3 | *.cachefile 4 | *.docstates 5 | *.ncrunchsolution 6 | *.pdb 7 | *.suo 8 | *.user 9 | bin/ 10 | obj/ 11 | _[Rr]e[Ss]harper.* 12 | *.bin 13 | *.nupkg -------------------------------------------------------------------------------- /AutoUpdateProjectsMinimumRequiredClickOnceVersion.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.5.002.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{522E6653-AA2F-4080-AB14-0FA4E6E84382}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "1 - TestProject - Before turning on automatic updates and enforce min version", "src\ChangesVisualStudioMakesToProjectFileThatNeedToBeMimicked\1 - TestProject - Before turning on automatic updates and enforce min version.csproj", "{09A4A572-9C19-4DB6-AE7F-613B62B0C535}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "2 - TestProject - After turning on min version", "src\ChangesVisualStudioMakesToProjectFileThatNeedToBeMimicked\2 - TestProject - After turning on min version.csproj", "{068ADA5A-54EB-4142-8C02-B949387F675C}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "3 - TestProject - After turning on automatic updates and enforce min version", "src\ChangesVisualStudioMakesToProjectFileThatNeedToBeMimicked\3 - TestProject - After turning on automatic updates and enforce min version.csproj", "{156C17E1-A9B0-4C17-B801-68F90FF49D7F}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "4 - TestProject - Already on the latest version", "src\ChangesVisualStudioMakesToProjectFileThatNeedToBeMimicked\4 - TestProject - Already on the latest version.csproj", "{C0D0E0E6-8303-41B0-82FC-303CF58EE74C}" 15 | EndProject 16 | Global 17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 18 | Debug|Any CPU = Debug|Any CPU 19 | Release|Any CPU = Release|Any CPU 20 | EndGlobalSection 21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 22 | {09A4A572-9C19-4DB6-AE7F-613B62B0C535}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {09A4A572-9C19-4DB6-AE7F-613B62B0C535}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {09A4A572-9C19-4DB6-AE7F-613B62B0C535}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {09A4A572-9C19-4DB6-AE7F-613B62B0C535}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {068ADA5A-54EB-4142-8C02-B949387F675C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {068ADA5A-54EB-4142-8C02-B949387F675C}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {068ADA5A-54EB-4142-8C02-B949387F675C}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {068ADA5A-54EB-4142-8C02-B949387F675C}.Release|Any CPU.Build.0 = Release|Any CPU 30 | {156C17E1-A9B0-4C17-B801-68F90FF49D7F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {156C17E1-A9B0-4C17-B801-68F90FF49D7F}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {156C17E1-A9B0-4C17-B801-68F90FF49D7F}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {156C17E1-A9B0-4C17-B801-68F90FF49D7F}.Release|Any CPU.Build.0 = Release|Any CPU 34 | {C0D0E0E6-8303-41B0-82FC-303CF58EE74C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 35 | {C0D0E0E6-8303-41B0-82FC-303CF58EE74C}.Debug|Any CPU.Build.0 = Debug|Any CPU 36 | {C0D0E0E6-8303-41B0-82FC-303CF58EE74C}.Release|Any CPU.ActiveCfg = Release|Any CPU 37 | {C0D0E0E6-8303-41B0-82FC-303CF58EE74C}.Release|Any CPU.Build.0 = Release|Any CPU 38 | EndGlobalSection 39 | GlobalSection(SolutionProperties) = preSolution 40 | HideSolutionNode = FALSE 41 | EndGlobalSection 42 | GlobalSection(NestedProjects) = preSolution 43 | {09A4A572-9C19-4DB6-AE7F-613B62B0C535} = {522E6653-AA2F-4080-AB14-0FA4E6E84382} 44 | {068ADA5A-54EB-4142-8C02-B949387F675C} = {522E6653-AA2F-4080-AB14-0FA4E6E84382} 45 | {156C17E1-A9B0-4C17-B801-68F90FF49D7F} = {522E6653-AA2F-4080-AB14-0FA4E6E84382} 46 | {C0D0E0E6-8303-41B0-82FC-303CF58EE74C} = {522E6653-AA2F-4080-AB14-0FA4E6E84382} 47 | EndGlobalSection 48 | GlobalSection(ExtensibilityGlobals) = postSolution 49 | SolutionGuid = {F12AB66E-08EA-4BA8-A53E-A3709EF46B72} 50 | EndGlobalSection 51 | EndGlobal 52 | -------------------------------------------------------------------------------- /License.md: -------------------------------------------------------------------------------- 1 | MIT 2 | Copyright (c) 2013 Daniel Schroeder, iQmetrix 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 5 | 6 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 7 | 8 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /ReadMe.md: -------------------------------------------------------------------------------- 1 | # 💬 Project Description 2 | 3 | Automatically force your ClickOnce app to update itself without prompting the user; this is less obtrusive to the user experience when receiving updates, and enhances security by ensuring the latest version is always used. 4 | 5 | This is a PowerShell script that updates the ClickOnce application's minimum required version to the latest published version. 6 | This will eliminate the prompt that asks the user if they want to download and install the latest version; instead the update will automatically be downloaded and installed. 7 | 8 | ## 💿 Installation 9 | 10 | The installation instructions below are intended to be used when publishing your ClickOnce app from Visual Studio. 11 | If you are looking to publish your ClickOnce app from a CI/CD pipeline, check out [this blog post](https://blog.danskingdom.com/continuously-deploy-your-clickonce-application-from-your-build-server/). 12 | 13 | ### .NET Framework Project and Packages.config Installation 14 | 15 | If you are using a .NET Framework project, as well as the `packages.config` package management format, simply install the [AutoUpdateProjectsMinimumRequiredClickOnceVersion NuGet package](https://nuget.org/packages/AutoUpdateProjectsMinimumRequiredClickOnceVersion) to your project, and it will automatically handle all of the installation for you. 16 | 17 | > NOTE: If you are using the PackageReference NuGet package management format, you will need to follow the manual installation instructions in the following section below. 18 | 19 | ![Navigate to Manage NuGet Packages](docs/Images/NavigateToManageNugetPackages.png) 20 | ![Install package window](docs/Images/InstallPackageWindow.png) 21 | ![File added to project](docs/Images/FileAddedToProject.png) 22 | 23 | As you can see in the last screenshot above, the NuGet package will add a `PostBuildScripts` folder to your project that contains the AutoUpdateProjectsMinimumRequiredClickOnceVersion.ps1 PowerShell script that is ran after each build. 24 | It also update's the project file to add a post-build event to run the PowerShell script. 25 | 26 | ### .NET Core Project / PackageReference Installation (e.g. .NET Core 3.1, .NET 5, .NET 6, etc.) 27 | 28 | .NET Core projects use the PackageReference NuGet package management format, where NuGet package references are stored directly in the project file instead of a separate `packages.config` file. 29 | Unfortunately the PackageReference format does not support NuGet packages running scripts during installation, so it cannot automatically add the required post-build event to the project. 30 | 31 | Instead of using the NuGet package, you will instead need to manually add the PowerShell script to your project, and add the post-build event to the project file. 32 | The steps to do this are: 33 | 34 | 1. In Visual Studio, right-click on your project and add a new folder called `PostBuildScripts`. 35 | 1. Download [the latest AutoUpdateProjectsMinimumRequiredClickOnceVersion.ps1 PowerShell script](https://github.com/deadlydog/AutoUpdateProjectsMinimumRequiredClickOnceVersion/releases) and save it to the `PostBuildScripts` folder. 36 | 1. You should now see the PowerShell script in the `PostBuildScripts` folder in Solution Explorer. 37 | 1. If you do not see the PowerShell file in Visual Studio, right-click on the `PostBuildScripts` folder and choose `Add` > `Existing Item...`. 38 | Select the PowerShell script that you downloaded and saved to the `PostBuildScripts` folder. 39 | 1. In Visual Studio, right-click on the project and choose `Properties`. 40 | 1. Navigate to the `Build` > `Events` tab, and paste the following code into the `Post-build event` text box: 41 | 42 | ```cmd 43 | REM Update the ClickOnce MinimumRequiredVersion so that it auto-updates without prompting. 44 | PowerShell -ExecutionPolicy Bypass -Command "& '$(ProjectDir)PostBuildScripts\AutoUpdateProjectsMinimumRequiredClickOnceVersion.ps1' -ProjectFilePaths '$(ProjectPath)'" 45 | ``` 46 | 47 | The end result should look like this: 48 | 49 | ![Add PowerShell file to project and add post-build event](docs/Images/AddScriptAndPostBuildEventToNetCoreProject.png) 50 | 51 | If you have multiple projects that you deploy via ClickOnce, you'll want to do the steps above for each project. 52 | 53 | ## ⚒ Additional ClickOnce Setup 54 | 55 | After the installation, if you haven't published your ClickOnce app yet, when you build your project it may fail with an error like: 56 | 57 | > `MSB3073` PowerShell script exited with code 1. 58 | 59 | If you check the `Output` pane in Visual Studio, it may mention that your project does not have any ClickOnce deployment settings in it. 60 | Before the build will succeed, you need to configure those settings. 61 | 62 | ### .NET Framework Project ClickOnce Settings 63 | 64 | .NET Framework projects store their ClickOnce settings in the project file. 65 | To configure the settings: 66 | 67 | 1. You can access the project settings by right-clicking the project in Visual Studio and choosing `Properties`. 68 | 1. In the project properties, on the `Publish` tab, in the `Updates...` button, make sure the following options are checked: 69 | 1. The application should check for updates 70 | 1. Specify a minimum required version for this application 71 | 72 | ![Set projects ClickOnce settings](docs/Images/SetProjectsClickOnceSettings.png) 73 | 74 | ### .NET Core Project ClickOnce Settings 75 | 76 | .NET Core projects store their ClickOnce settings in a publish profile xml file. 77 | To configure the settings: 78 | 79 | 1. You can edit the publish profile settings by right-clicking the project in Visual Studio and choosing `Publish...` to get to the wizard. 80 | 1. If you have multiple publish profiles, choose the appropriate ClickOnce profile, or create a new one. 81 | 1. In the Publish wizard, within the `Settings` tab, make sure the following options are checked: 82 | 1. The application should check for updates 83 | 1. In the `Update Settings` window, Specify a minimum required version for this application 84 | 85 | ![Set .NET Core publish profiles ClickOnce settings](docs/Images/SetNetCorePublishWizardClickOnceSettings.png) 86 | 87 | ## 🤔 Troubleshooting 88 | 89 | If for some reason the script is not updating your project's MinimumRequiredVersion to the latest published version, check the Visual Studio `Output` window for error messages thrown by the PowerShell script. 90 | 91 | ## 📃 Manually Running The PowerShell Script 92 | 93 | Detailed help documentation for manually running [the PowerShell script](/src/AutoUpdateProjectsMinimumRequiredClickOnceVersion.ps1) can be obtained by running the Get-Help cmdlet against the script in a PowerShell window. 94 | 95 | For example, open up a Windows PowerShell command prompt, navigate to the folder containing the AutoUpdateProjectsMinimumRequiredClickOnceVersion.ps1 script, and enter: 96 | 97 | ```powershell 98 | Get-Help .\AutoUpdateProjectsMinimumRequiredClickOnceVersion.ps1 -Detailed 99 | ``` 100 | 101 | ## 😎 Tips 102 | 103 | The first build after each ClickOnce deployment will update the .csproj file, and the project will need to be reloaded. 104 | If you are running an older version of Visual Studio (2012 or earlier), to prevent the reloading of the project from closing any tabs that you have open I recommend installing the [Workspace Reloader Visual Studio extension](http://visualstudiogallery.msdn.microsoft.com/6705affd-ca37-4445-9693-f3d680c92f38). 105 | 106 | ## 💳 Donate 107 | 108 | Buy me a hot chocolate for providing this project open source and for free 🙂 109 | 110 | [![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=8Y2HFLM7G5LJY) 111 | -------------------------------------------------------------------------------- /docs/Images/AddScriptAndPostBuildEventToNetCoreProject.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deadlydog/AutoUpdateProjectsMinimumRequiredClickOnceVersion/f0b8b219584e690bb2593001f9593bd44e92e06e/docs/Images/AddScriptAndPostBuildEventToNetCoreProject.png -------------------------------------------------------------------------------- /docs/Images/FileAddedToProject.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deadlydog/AutoUpdateProjectsMinimumRequiredClickOnceVersion/f0b8b219584e690bb2593001f9593bd44e92e06e/docs/Images/FileAddedToProject.png -------------------------------------------------------------------------------- /docs/Images/InstallPackageWindow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deadlydog/AutoUpdateProjectsMinimumRequiredClickOnceVersion/f0b8b219584e690bb2593001f9593bd44e92e06e/docs/Images/InstallPackageWindow.png -------------------------------------------------------------------------------- /docs/Images/NavigateToManageNugetPackages.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deadlydog/AutoUpdateProjectsMinimumRequiredClickOnceVersion/f0b8b219584e690bb2593001f9593bd44e92e06e/docs/Images/NavigateToManageNugetPackages.png -------------------------------------------------------------------------------- /docs/Images/SetNetCorePublishWizardClickOnceSettings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deadlydog/AutoUpdateProjectsMinimumRequiredClickOnceVersion/f0b8b219584e690bb2593001f9593bd44e92e06e/docs/Images/SetNetCorePublishWizardClickOnceSettings.png -------------------------------------------------------------------------------- /docs/Images/SetProjectsClickOnceSettings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deadlydog/AutoUpdateProjectsMinimumRequiredClickOnceVersion/f0b8b219584e690bb2593001f9593bd44e92e06e/docs/Images/SetProjectsClickOnceSettings.png -------------------------------------------------------------------------------- /src/AutoUpdateProjectsMinimumRequiredClickOnceVersion.ps1: -------------------------------------------------------------------------------- 1 | #Requires -Version 2.0 2 | <# 3 | .SYNOPSIS 4 | This script finds the current ClickOnce version in a project file (.csproj or .vbproj) or a publish profile file (.pubxml), and updates the MinimumRequiredVersion to be this same version. 5 | 6 | .DESCRIPTION 7 | This script finds the current ClickOnce version in a project file (.csproj or .vbproj) or a publish profile file (.pubxml), and updates the MinimumRequiredVersion to be this same version. 8 | Setting the MinimumRequiredVersion property forces the ClickOnce application to update automatically without prompting the user. 9 | 10 | You can also dot source this script in order to call the UpdateProjectsMinimumRequiredClickOnceVersion function directly. 11 | 12 | .PARAMETER ProjectFilePaths 13 | Array of paths of the .csproj, .vbproj or .pubxml files to process. 14 | If not provided the script will search for and process all project files and publish profile files in the same directory as the script. 15 | 16 | .PARAMETER DotSource 17 | Provide this switch when dot sourcing the script, so that the script does not actually run. 18 | Dot sourcing the script will allow you to directly call the UpdateProjectsMinimumRequiredClickOnceVersion function. 19 | 20 | .EXAMPLE 21 | Update all project files and publish profile files in the same directory as this script. 22 | 23 | & .\AutoUpdateProjectsMinimumRequiredClickOnceVersion.ps1 24 | 25 | .EXAMPLE 26 | Pass in a project file. 27 | 28 | & .\AutoUpdateProjectsMinimumRequiredClickOnceVersion.ps1 -ProjectFilePaths "C:\Some project.csproj" 29 | 30 | .EXAMPLE 31 | Pass in multiple project files, using the -ProjectFilePaths alias "-p". 32 | 33 | & .\AutoUpdateProjectsMinimumRequiredClickOnceVersion.ps1 -p "C:\Some project.csproj","C:\Another project.vbproj" 34 | 35 | .EXAMPLE 36 | Pipe multiple project files in. 37 | 38 | "C:\Some project.csproj","C:\Another project.vbproj" | & .\AutoUpdateProjectsMinimumRequiredClickOnceVersion.ps1 39 | 40 | .EXAMPLE 41 | Dot source the script into your script, allowing the UpdateProjectsMinimumRequiredClickOnceVersion function to be called directly. 42 | Here we first dot source the script, providing the -DotSource switch so that the script does not try to process an files. 43 | We then process 4 project files; 2 via the ProjectFilePath parameter, and 2 via piping. 44 | 45 | . .\AutoUpdateProjectsMinimumRequiredClickOnceVersion.ps1 -DotSource 46 | UpdateProjectsMinimumRequiredClickOnceVersion -ProjectFilePath "C:\Some project.csproj","C:\Another project.vbproj" 47 | "C:\Yet another project.csproj","C:\And another project.vbproj" | UpdateProjectsMinimumRequiredClickOnceVersion 48 | 49 | .LINK 50 | Project Home: https://github.com/deadlydog/AutoUpdateProjectsMinimumRequiredClickOnceVersion 51 | 52 | .NOTES 53 | Author: Daniel Schroeder 54 | Version: 1.7.1 55 | #> 56 | 57 | Param 58 | ( 59 | [Parameter(Position=0, Mandatory=$false, ValueFromPipeline=$true, HelpMessage="Array of paths of the .csproj, .vbproj or .pubxml files to process.")] 60 | [Alias("p")] 61 | [string[]] $ProjectFilePaths, 62 | 63 | [Parameter(Position=1, Mandatory=$false, HelpMessage="Provide this switch when dot sourcing the script.")] 64 | [Alias("d")] 65 | [switch] $DotSource 66 | ) 67 | 68 | Begin 69 | { 70 | # Turn on Strict Mode to help catch syntax-related errors. 71 | # This must come after a script's/function's param section. 72 | # Forces a function to be the first non-comment code to appear in a PowerShell Module. 73 | Set-StrictMode -Version Latest 74 | 75 | function UpdateProjectsMinimumRequiredClickOnceVersion 76 | { 77 | Param 78 | ( 79 | [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, HelpMessage="The project file (.csproj or .vbproj) or publish profile file (.pubxml) to update.")] 80 | [ValidatePattern('(.csproj|.vbproj|.pubxml)$')] 81 | [ValidateScript({Test-Path $_ -PathType Leaf})] 82 | [Alias("p")] 83 | [string] $ProjectFilePath 84 | ) 85 | 86 | Begin 87 | { 88 | # Build the regular expressions to find the information we will need. 89 | $rxMinimumRequiredVersionTag = New-Object System.Text.RegularExpressions.Regex "\(?.*?)\", SingleLine 90 | $rxApplicationVersionTag = New-Object System.Text.RegularExpressions.Regex "\(?\d+\.\d+\.\d+\.).*?\", SingleLine 91 | $rxApplicationRevisionTag = New-Object System.Text.RegularExpressions.Regex "\(?[0-9]+)\", SingleLine 92 | $rxVersionNumber = [regex] "\d+\.\d+\.\d+\.\d+" 93 | $rxUpdateRequiredTag = New-Object System.Text.RegularExpressions.Regex "\(?.*?)\", SingleLine 94 | $rxUpdateEnabledTag = New-Object System.Text.RegularExpressions.Regex "\(?.*?)\", SingleLine 95 | } 96 | 97 | Process 98 | { 99 | # Catch any unhandled exceptions, write its error message, and exit the process with a non-zero error code to indicate failure. 100 | trap [Exception] 101 | { 102 | [string]$errorMessage = [string]$_ 103 | [int]$exitCode = 1 104 | 105 | # If this is one of our custom exceptions, strip the error code off of the front. 106 | if ([string]$errorMessage.SubString(0, 1) -match "\d") 107 | { 108 | $exitCode = [string]$errorMessage.SubString(0, 1) 109 | $errorMessage = [string]$errorMessage.SubString(1) 110 | } 111 | 112 | $errorMessage += ' See the project homepage for more details: https://github.com/deadlydog/AutoUpdateProjectsMinimumRequiredClickOnceVersion' 113 | 114 | # Write the error message and exit with an error code so that the Visual Studio build fails and the user notices that something is wrong. 115 | Write-Error $errorMessage 116 | exit [int]$exitCode 117 | } 118 | 119 | # Read the file contents in. 120 | $text = [System.IO.File]::ReadAllText($ProjectFilePath) 121 | 122 | # Get the current Minimum Required Version, and the Version that it should be. 123 | $oldMinimumRequiredVersion = $rxMinimumRequiredVersionTag.Match($text).Groups["Version"].Value 124 | $majorMinorBuild = $rxApplicationVersionTag.Match($text).Groups["Version"].Value 125 | $revision = $rxApplicationRevisionTag.Match($text).Groups["Revision"].Value 126 | $newMinimumRequiredVersion = [string]$majorMinorBuild + $revision 127 | 128 | # Get the Tag matches that we might need during the script. 129 | $applicationVersionTagMatch = $rxApplicationVersionTag.Match($text) 130 | $updateRequiredTagMatch = $rxUpdateRequiredTag.Match($text) 131 | $updateEnabledTagMatch = $rxUpdateEnabledTag.Match($text) 132 | 133 | # If there was a problem constructing the new version number, throw an error. 134 | if (-not $rxVersionNumber.Match($newMinimumRequiredVersion).Success) 135 | { 136 | throw "2'$ProjectFilePath' does not appear to have any ClickOnce deployment settings in it. You must publish the project at least once to create the ClickOnce deployment settings." 137 | } 138 | 139 | # If we couldn't find the old Minimum Required Version (i.e. it isn't setup in the project yet), add it. 140 | if (-not $rxVersionNumber.Match($oldMinimumRequiredVersion).Success) 141 | { 142 | # If we can get the Application Version Tag and the Update Required tag. 143 | if ($applicationVersionTagMatch.Success -and $updateRequiredTagMatch.Success) 144 | { 145 | # Add the Minimum Required Version tag after the Application Version Tag. 146 | $text = $rxApplicationVersionTag.Replace($text, $applicationVersionTagMatch.Value + "`n`t" + $newMinimumRequiredVersion + "") 147 | 148 | # Make sure Update Required is set to true. 149 | $text = $rxUpdateRequiredTag.Replace($text, "true") 150 | } 151 | # Else throw an error to have the user setup the Minimum Required Version manually. 152 | else 153 | { 154 | throw "3'$ProjectFilePath' is not currently set to enforce a MinimumRequiredVersion. To fix this in Visual Studio go to the Project's Properties->Publish->Updates... and check off 'Specify a minimum required version for this application'." 155 | } 156 | } 157 | 158 | # If the Updates Enabled tag is defined, check its value. 159 | if ($updateEnabledTagMatch.Success) 160 | { 161 | # If the application has updates disabled, enable them. 162 | if ($updateEnabledTagMatch.Groups["BoolValue"].Value -ne "true") 163 | { 164 | $text = $rxUpdateEnabledTag.Replace($text, "true") 165 | } 166 | } 167 | # Else the Updates Enabled tag is not defined, so if the Application Version tag is defined, add it below that one. 168 | elseif ($applicationVersionTagMatch.Success) 169 | { 170 | $text = $rxApplicationVersionTag.Replace($text, $applicationVersionTagMatch.Value + "`n`ttrue") 171 | } 172 | # Else the Updates Enabled and Application Version tags are not defined, so throw error to have user turn on automatic updates manually. 173 | else 174 | { 175 | throw "4'$ProjectFilePath' is not currently set to allow automatic updates. To fix this in Visual Studio go to the Project's Properties->Publish->Updates... and check off 'The application should check for updates'." 176 | } 177 | 178 | # Only write to the file if it is not already up to date. 179 | if ($newMinimumRequiredVersion -eq $oldMinimumRequiredVersion) 180 | { 181 | Write-Host "The Minimum Required Version of '$ProjectFilePath' is already up-to-date on version '$newMinimumRequiredVersion'." 182 | } 183 | else 184 | { 185 | # Check the file out of TFS before writing to it. 186 | Tfs-Checkout -Path $ProjectFilePath 187 | 188 | # Update the file contents and write them back to the file. 189 | $text = $rxMinimumRequiredVersionTag.Replace($text, "" + $newMinimumRequiredVersion + "") 190 | [System.IO.File]::WriteAllText($ProjectFilePath, $text) 191 | Write-Host "Updated Minimum Required Version of '$ProjectFilePath' from '$oldMinimumRequiredVersion' to '$newMinimumRequiredVersion'" 192 | } 193 | } 194 | } 195 | 196 | function Tfs-Checkout 197 | { 198 | param 199 | ( 200 | [Parameter(Mandatory=$true, Position=0, HelpMessage="The local path to the file or folder to checkout from TFS source control.")] 201 | [string]$Path, 202 | 203 | [switch]$Recursive 204 | ) 205 | 206 | trap [Exception] 207 | { 208 | # Write out any errors that occur when attempting to do the checkout, and then allow the script to continue as usual. 209 | Write-Warning [string]$_ 210 | } 211 | 212 | [string] $tfExecutablePath = Get-TfExecutablePath 213 | 214 | if ([string]::IsNullOrEmpty($tfExecutablePath)) 215 | { 216 | throw 'Could not locate TF.exe to check files out of Team Foundation Version Control if necessary.' 217 | } 218 | 219 | $output = & "$tfExecutablePath" workfold "$Path" 2>&1 220 | if ($output -like '*Unable to determine the source control*') 221 | { 222 | return 223 | } 224 | 225 | # Check the file out of TFS. 226 | if ($Recursive) 227 | { & "$tfExecutablePath" checkout "$Path" /recursive } 228 | else 229 | { & "$tfExecutablePath" checkout "$Path" } 230 | } 231 | 232 | function Get-TfExecutablePath 233 | { 234 | [string] $tfPath = Get-TfExecutablePathForVisualStudio2017AndNewer 235 | 236 | if ([string]::IsNullOrEmpty($tfPath)) 237 | { 238 | $tfPath = Get-TfExecutablePathForVisualStudio2015AndOlder 239 | } 240 | 241 | return $tfPath 242 | } 243 | 244 | function Get-TfExecutablePathForVisualStudio2015AndOlder 245 | { 246 | # Get the Visual Studio IDE paths from latest to oldest. 247 | [string[]] $vsCommonToolsPaths = @( 248 | $env:VS140COMNTOOLS 249 | $env:VS120COMNTOOLS 250 | $env:VS110COMNTOOLS 251 | $env:VS100COMNTOOLS 252 | ) 253 | $vsCommonToolsPaths = @($vsCommonToolsPaths | Where-Object { $_ -ne $null }) 254 | 255 | # Try and find the latest TF.exe. 256 | [string] $tfPath = $null 257 | foreach ($vsCommonToolsPath in $vsCommonToolsPaths) 258 | { 259 | [string] $potentialTfPath = Join-Path -Path $vsCommonToolsPath -ChildPath '..\IDE\tf.exe' 260 | if (Test-Path -Path $potentialTfPath -PathType Leaf) 261 | { 262 | $tfPath = ($potentialTfPath | Resolve-Path) 263 | break 264 | } 265 | } 266 | 267 | return $tfPath 268 | } 269 | 270 | function Get-TfExecutablePathForVisualStudio2017AndNewer 271 | { 272 | # Later we can probably make use of the VSSetup.PowerShell module to find the MsBuild.exe: https://github.com/Microsoft/vssetup.powershell 273 | # Or perhaps the VsWhere.exe: https://github.com/Microsoft/vswhere 274 | # But for now, to keep this script PowerShell 2.0 compatible and not rely on external executables, let's look for it ourselves in known locations. 275 | # Example of known locations: 276 | # "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe" 277 | 278 | [string] $visualStudioDirectoryPath = Get-CommonVisualStudioDirectoryPath 279 | [bool] $visualStudioDirectoryPathDoesNotExist = [string]::IsNullOrEmpty($visualStudioDirectoryPath) 280 | if ($visualStudioDirectoryPathDoesNotExist) 281 | { 282 | return $null 283 | } 284 | 285 | # First search for the VS Command Prompt in the expected locations (faster). 286 | $expectedTfPathWithWildcards = "$visualStudioDirectoryPath\*\*\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe" 287 | $tfPathObjects = Get-Item -Path $expectedTfPathWithWildcards 288 | 289 | [bool] $vsCommandPromptWasNotFound = ($null -eq $tfPathObjects) -or ($tfPathObjects.Length -eq 0) 290 | if ($vsCommandPromptWasNotFound) 291 | { 292 | # Recursively search the entire Microsoft Visual Studio directory for the VS Command Prompt (slower, but will still work if MS changes folder structure). 293 | Write-Verbose "The Visual Studio Command Prompt was not found at an expected location. Searching more locations, but this will be a little slow." -Verbose 294 | $tfPathObjects = Get-ChildItem -Path $visualStudioDirectoryPath -Recurse | Where-Object { $_.Name -ieq 'TF.exe' } 295 | } 296 | 297 | $tfPathObjectsSortedWithNewestVersionsFirst = $tfPathObjects | Sort-Object -Property FullName -Descending 298 | 299 | $newestTfPath = $tfPathObjectsSortedWithNewestVersionsFirst | Select-Object -ExpandProperty FullName -First 1 300 | return $newestTfPath 301 | } 302 | 303 | function Get-CommonVisualStudioDirectoryPath 304 | { 305 | [string] $programFilesDirectory = $null 306 | try 307 | { 308 | $programFilesDirectory = Get-Item 'Env:\ProgramFiles(x86)' -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Value 309 | } 310 | catch 311 | { } 312 | 313 | if ([string]::IsNullOrEmpty($programFilesDirectory)) 314 | { 315 | $programFilesDirectory = 'C:\Program Files (x86)' 316 | } 317 | 318 | # If we're on a 32-bit machine, we need to go straight after the "Program Files" directory. 319 | if (!(Test-Path -LiteralPath $programFilesDirectory -PathType Container)) 320 | { 321 | try 322 | { 323 | $programFilesDirectory = Get-Item 'Env:\ProgramFiles' -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Value 324 | } 325 | catch 326 | { 327 | $programFilesDirectory = $null 328 | } 329 | 330 | if ([string]::IsNullOrEmpty($programFilesDirectory)) 331 | { 332 | $programFilesDirectory = 'C:\Program Files' 333 | } 334 | } 335 | 336 | [string] $visualStudioDirectoryPath = Join-Path -Path $programFilesDirectory -ChildPath 'Microsoft Visual Studio' 337 | 338 | [bool] $visualStudioDirectoryPathExists = (Test-Path -LiteralPath $visualStudioDirectoryPath -PathType Container) 339 | if (!$visualStudioDirectoryPathExists) 340 | { 341 | return $null 342 | } 343 | return $visualStudioDirectoryPath 344 | } 345 | } 346 | 347 | Process 348 | { 349 | # If we shouldn't actually run the script, then just exit. 350 | if ($DotSource) 351 | { 352 | return 353 | } 354 | 355 | # If a path to a project file was not provided, grab all of the project files in the same directory as this script. 356 | if (-not($ProjectFilePaths)) 357 | { 358 | # Get the directory that this script is in. 359 | $scriptDirectory = Split-Path $MyInvocation.MyCommand.Path -Parent 360 | 361 | # Get all of the project files in the same directory as this script. 362 | $ProjectFilePaths = @() 363 | Get-Item "$scriptDirectory\*" -Include "*.csproj","*.vbproj","*.pubxml" | 364 | ForEach-Object { $ProjectFilePaths += $_.FullName } 365 | } 366 | 367 | # If there are no files to process, display a message. 368 | if (-not($ProjectFilePaths)) 369 | { 370 | throw "No project files were found to be processed." 371 | } 372 | 373 | # .NET Core stores the settings in a publish profile instead of directly in the project file, so we need to grab those too. 374 | [string[]] $filePathsToProcess = $ProjectFilePaths 375 | 376 | # Get any publish profiles for each of the projects. 377 | $ProjectFilePaths | ForEach-Object { 378 | [string] $projectDirectory = Split-Path -Path $_ -Parent 379 | [string] $publishProfilesDirectory = Join-Path -Path $projectDirectory -ChildPath 'Properties\PublishProfiles' 380 | if (Test-Path -Path $publishProfilesDirectory -PathType Container) 381 | { 382 | Get-Item "$publishProfilesDirectory\*" -Include "*.pubxml" | 383 | ForEach-Object { $filePathsToProcess += $_.FullName } 384 | } 385 | } 386 | 387 | # Process each of the project and publish profile files. 388 | $filePathsToProcess | UpdateProjectsMinimumRequiredClickOnceVersion 389 | } 390 | -------------------------------------------------------------------------------- /src/ChangesVisualStudioMakesToProjectFileThatNeedToBeMimicked/1 - TestProject - Before turning on automatic updates and enforce min version.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {24046B28-2F75-423F-894A-2F68C5B90A0E} 8 | WinExe 9 | Properties 10 | WpfApplication1 11 | WpfApplication1 12 | v4.5 13 | 512 14 | {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 15 | 4 16 | 17 | 18 | AnyCPU 19 | true 20 | full 21 | false 22 | bin\Debug\ 23 | DEBUG;TRACE 24 | prompt 25 | 4 26 | 27 | 28 | AnyCPU 29 | pdbonly 30 | true 31 | bin\Release\ 32 | TRACE 33 | prompt 34 | 4 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 4.0 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | MSBuild:Compile 54 | Designer 55 | 56 | 57 | MSBuild:Compile 58 | Designer 59 | 60 | 61 | App.xaml 62 | Code 63 | 64 | 65 | MainWindow.xaml 66 | Code 67 | 68 | 69 | 70 | 71 | Code 72 | 73 | 74 | True 75 | True 76 | Resources.resx 77 | 78 | 79 | True 80 | Settings.settings 81 | True 82 | 83 | 84 | ResXFileCodeGenerator 85 | Resources.Designer.cs 86 | 87 | 88 | SettingsSingleFileGenerator 89 | Settings.Designer.cs 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 104 | -------------------------------------------------------------------------------- /src/ChangesVisualStudioMakesToProjectFileThatNeedToBeMimicked/2 - TestProject - After turning on min version.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {24046B28-2F75-423F-894A-2F68C5B90A0E} 8 | WinExe 9 | Properties 10 | WpfApplication1 11 | WpfApplication1 12 | v4.5 13 | 512 14 | {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 15 | 4 16 | publish\ 17 | true 18 | Disk 19 | false 20 | Foreground 21 | 7 22 | Days 23 | false 24 | true 25 | true 26 | 1.0.0.0 27 | 1 28 | 1.0.0.%2a 29 | false 30 | false 31 | true 32 | 33 | 34 | AnyCPU 35 | true 36 | full 37 | false 38 | bin\Debug\ 39 | DEBUG;TRACE 40 | prompt 41 | 4 42 | 43 | 44 | AnyCPU 45 | pdbonly 46 | true 47 | bin\Release\ 48 | TRACE 49 | prompt 50 | 4 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 4.0 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | MSBuild:Compile 70 | Designer 71 | 72 | 73 | MSBuild:Compile 74 | Designer 75 | 76 | 77 | App.xaml 78 | Code 79 | 80 | 81 | MainWindow.xaml 82 | Code 83 | 84 | 85 | 86 | 87 | Code 88 | 89 | 90 | True 91 | True 92 | Resources.resx 93 | 94 | 95 | True 96 | Settings.settings 97 | True 98 | 99 | 100 | ResXFileCodeGenerator 101 | Resources.Designer.cs 102 | 103 | 104 | SettingsSingleFileGenerator 105 | Settings.Designer.cs 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | False 115 | Microsoft .NET Framework 4.5 %28x86 and x64%29 116 | true 117 | 118 | 119 | False 120 | .NET Framework 3.5 SP1 Client Profile 121 | false 122 | 123 | 124 | False 125 | .NET Framework 3.5 SP1 126 | false 127 | 128 | 129 | 130 | 137 | -------------------------------------------------------------------------------- /src/ChangesVisualStudioMakesToProjectFileThatNeedToBeMimicked/3 - TestProject - After turning on automatic updates and enforce min version.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {24046B28-2F75-423F-894A-2F68C5B90A0E} 8 | WinExe 9 | Properties 10 | WpfApplication1 11 | WpfApplication1 12 | v4.5 13 | 512 14 | {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 15 | 4 16 | false 17 | publish\ 18 | true 19 | Disk 20 | true 21 | Foreground 22 | 7 23 | Days 24 | false 25 | true 26 | true 27 | 1.0.0.0 28 | 1 29 | 1.0.0.%2a 30 | false 31 | true 32 | 33 | 34 | AnyCPU 35 | true 36 | full 37 | false 38 | bin\Debug\ 39 | DEBUG;TRACE 40 | prompt 41 | 4 42 | 43 | 44 | AnyCPU 45 | pdbonly 46 | true 47 | bin\Release\ 48 | TRACE 49 | prompt 50 | 4 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 4.0 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | MSBuild:Compile 70 | Designer 71 | 72 | 73 | MSBuild:Compile 74 | Designer 75 | 76 | 77 | App.xaml 78 | Code 79 | 80 | 81 | MainWindow.xaml 82 | Code 83 | 84 | 85 | 86 | 87 | Code 88 | 89 | 90 | True 91 | True 92 | Resources.resx 93 | 94 | 95 | True 96 | Settings.settings 97 | True 98 | 99 | 100 | ResXFileCodeGenerator 101 | Resources.Designer.cs 102 | 103 | 104 | SettingsSingleFileGenerator 105 | Settings.Designer.cs 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | False 115 | Microsoft .NET Framework 4.5 %28x86 and x64%29 116 | true 117 | 118 | 119 | False 120 | .NET Framework 3.5 SP1 Client Profile 121 | false 122 | 123 | 124 | False 125 | .NET Framework 3.5 SP1 126 | false 127 | 128 | 129 | 130 | 137 | -------------------------------------------------------------------------------- /src/ChangesVisualStudioMakesToProjectFileThatNeedToBeMimicked/4 - TestProject - Already on the latest version.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {24046B28-2F75-423F-894A-2F68C5B90A0E} 8 | WinExe 9 | Properties 10 | WpfApplication1 11 | WpfApplication1 12 | v4.5 13 | 512 14 | {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 15 | 4 16 | false 17 | publish\ 18 | true 19 | Disk 20 | true 21 | Foreground 22 | 7 23 | Days 24 | false 25 | true 26 | true 27 | 1.0.0.1 28 | 1 29 | 1.0.0.%2a 30 | false 31 | true 32 | 33 | 34 | AnyCPU 35 | true 36 | full 37 | false 38 | bin\Debug\ 39 | DEBUG;TRACE 40 | prompt 41 | 4 42 | 43 | 44 | AnyCPU 45 | pdbonly 46 | true 47 | bin\Release\ 48 | TRACE 49 | prompt 50 | 4 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 4.0 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | MSBuild:Compile 70 | Designer 71 | 72 | 73 | MSBuild:Compile 74 | Designer 75 | 76 | 77 | App.xaml 78 | Code 79 | 80 | 81 | MainWindow.xaml 82 | Code 83 | 84 | 85 | 86 | 87 | Code 88 | 89 | 90 | True 91 | True 92 | Resources.resx 93 | 94 | 95 | True 96 | Settings.settings 97 | True 98 | 99 | 100 | ResXFileCodeGenerator 101 | Resources.Designer.cs 102 | 103 | 104 | SettingsSingleFileGenerator 105 | Settings.Designer.cs 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | False 115 | Microsoft .NET Framework 4.5 %28x86 and x64%29 116 | true 117 | 118 | 119 | False 120 | .NET Framework 3.5 SP1 Client Profile 121 | false 122 | 123 | 124 | False 125 | .NET Framework 3.5 SP1 126 | false 127 | 128 | 129 | 130 | 137 | -------------------------------------------------------------------------------- /tools/PublishNewNuGetPackage/AutoUpdateProjectsMinimumRequiredClickOnceVersion.nuspec: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | AutoUpdateProjectsMinimumRequiredClickOnceVersion 5 | 1.2.2 6 | AutoUpdateProjectsMinimumRequiredClickOnceVersion 7 | Daniel Schroeder,iQmetrix 8 | Daniel Schroeder,iQmetrix 9 | MIT 10 | https://github.com/deadlydog/AutoUpdateProjectsMinimumRequiredClickOnceVersion 11 | false 12 | Automatically force your ClickOnce app to update itself without prompting the user, making a less obtrusive end-user experience, and guaranteeing they are always using the latest version of the application. 13 | Adds a post-build event to the project to run a PowerShell script that updates the ClickOnce project's minimum required version in the .csproj/.vbproj file to the latest published version. 14 | Because the PowerShell script modifies the .csproj/.vbproj file outside of Visual Studio, the first time you do a build after publishing a new ClickOnce version, if you have any files from that project open you will be prompted to reload the project. In order to prevent this from closing your open tabs, I recommend installing Scott Hanselman’s Workspace Reloader Visual Studio extension. 15 | If it does not seem to be working or causes the build to fail, check the Output window for any errors that may have occurred. 16 | Automatically force your ClickOnce app to update to the latest version without prompting the user. 17 | - Fix bug that would result in an error if the project did not have a PublishProfiles directory. 18 | Daniel Schroeder 2013 19 | ClickOnce Click Once Auto Automatic Automatically Update Project Minimum Min Required Version PowerShell Power Shell 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /tools/PublishNewNuGetPackage/New-NuGetPackage.ps1: -------------------------------------------------------------------------------- 1 | #Requires -Version 2.0 2 | <# 3 | .SYNOPSIS 4 | Creates a NuGet Package (.nupkg) file from the given Project or NuSpec file, and optionally uploads it to a NuGet Gallery. 5 | 6 | .DESCRIPTION 7 | Creates a NuGet Package (.nupkg) file from the given Project or NuSpec file. 8 | Additional parameters may be provided to also upload the new NuGet package to a NuGet Gallery. 9 | If an "-OutputDirectory" is not provided via the PackOptions parameter, the default is to place the .nupkg file in a "New-NuGetPackages" directory in the same directory as the .nuspec or project file being packed. 10 | If a NuGet Package file is specified (rather than a Project or NuSpec file), we will simply push that package to the NuGet Gallery. 11 | 12 | .PARAMETER NuSpecFilePath 13 | The path to the .nuspec file to pack. 14 | If you intend to pack a project file that has an accompanying .nuspec file, use the ProjectFilePath parameter instead. 15 | 16 | .PARAMETER ProjectFilePath 17 | The path to the project file (e.g. .csproj, .vbproj, .fsproj) to pack. 18 | If packing a project file that has an accompanying .nuspec file, the nuspec file will automatically be picked up by the NuGet executable. 19 | 20 | .PARAMETER PackageFilePath 21 | The path to the NuGet package file (.nupkg) to push to the NuGet gallery. 22 | If provided a new package will not be created; we will simply push to specified NuGet package to the NuGet gallery. 23 | 24 | .PARAMETER VersionNumber 25 | The version number to use for the NuGet package. 26 | The version element in the .nuspec file (if available) will be updated with the given value unless the DoNotUpdateNuSpecFile switch is provided. 27 | If this parameter is not provided then you will be prompted for the version number to use (unless the NoPrompt or NoPromptForVersionNumber switch is provided). 28 | If the "-Version" parameter is provided in the PackOptions, that version will be used for the NuGet package, but this version will be used to update the .nuspec file (if available). 29 | 30 | .PARAMETER ReleaseNotes 31 | The release notes to use for the NuGet package. 32 | The release notes element in the .nuspec file (if available) will be updated with the given value unless the DoNotUpdateNuSpecFile switch is provided. 33 | 34 | .PARAMETER PackOptions 35 | The arguments to pass to NuGet's Pack command. These will be passed to the NuGet executable as-is, so be sure to follow the NuGet's required syntax. 36 | By default this is set to "-Build" in order to be able to create a package from a project that has not been manually built yet. 37 | See http://docs.nuget.org/docs/reference/command-line-reference for valid parameters. 38 | 39 | .PARAMETER PushPackageToNuGetGallery 40 | If this switch is provided the NuGet package will be pushed to the NuGet gallery. 41 | Use the PushOptions to specify a custom gallery to push to, or an API key if required. 42 | 43 | .PARAMETER PushOptions 44 | The arguments to pass to NuGet's Push command. These will be passed to the NuGet executable as-is, so be sure to follow the NuGet's required syntax. 45 | See http://docs.nuget.org/docs/reference/command-line-reference for valid parameters. 46 | 47 | .PARAMETER DeletePackageAfterPush 48 | If this switch is provided and the package is successfully pushed to a NuGet gallery, the NuGet package file will then be deleted. 49 | 50 | .PARAMETER NoPrompt 51 | If this switch is provided the user will not be prompted for the version number or release notes; the current ones in the .nuspec file will be used (if available). 52 | The user will not be prompted for any other form of input either, such as if they want to push the package to a gallery, or to give input before the script exits when an error occurs. 53 | This parameter should be provided when an automated mechanism is running this script (e.g. an automated build system). 54 | 55 | .PARAMETER NoPromptExceptOnError 56 | The same as NoPrompt except if an error occurs the user will be prompted for input before the script exists, making sure they are notified that an error occurred. 57 | If both this and the NoPrompt switch are provided, the NoPrompt switch will be used. 58 | If both this and the NoPromptForInputOnError switch are provided, it is the same as providing the NoPrompt switch. 59 | 60 | .PARAMETER NoPromptForVersionNumber 61 | If this switch is provided the user will not be prompted for the version number; the one in the .nuspec file will be used (if available). 62 | 63 | .PARAMETER NoPromptForReleaseNotes 64 | If this switch is provided the user will not be prompted for the release notes; the ones in the .nuspec file will be used (if available). 65 | 66 | .PARAMETER NoPromptForPushPackageToNuGetGallery 67 | If this switch is provided the user will not be asked if they want to push the new package to the NuGet Gallery when the PushPackageToNuGetGallery switch is not provided. 68 | 69 | .PARAMETER NoPromptForInputOnError 70 | If this switch is provided the user will not be prompted for input before the script exits when an error occurs, so they may not notice than an error occurred. 71 | 72 | .PARAMETER UsePowerShellPrompts 73 | If this switch is provided any prompts for user input will be made via the PowerShell console, rather than the regular GUI components. 74 | This may be preferable when attempting to pipe input into the cmdlet. 75 | 76 | .PARAMETER DoNotUpdateNuSpecFile 77 | If this switch is provided a backup of the .nuspec file (if available) will be made, changes will be made to the original .nuspec file in order to 78 | properly perform the pack, and then the original file will be restored once the pack is complete. 79 | 80 | .PARAMETER NuGetExecutableFilePath 81 | The full path to NuGet.exe. 82 | If not provided it is assumed that NuGet.exe is in the same directory as this script, or that NuGet.exe has been added to your PATH and can be called directly from the command prompt. 83 | 84 | .PARAMETER UpdateNuGetExecutable 85 | If this switch is provided "NuGet.exe update -self" will be performed before packing or pushing anything. 86 | Provide this switch to ensure your NuGet executable is always up-to-date on the latest version. 87 | 88 | .PARAMETER TfExecutableFilePath 89 | The full path to TF.exe. 90 | If not provided the script will attempt to locate the Visual Studio installation directory and use the TF.exe file from there. 91 | 92 | .EXAMPLE 93 | & .\New-NuGetPackage.ps1 94 | 95 | Run the script without any parameters (e.g. as if it was ran directly from Windows Explorer). 96 | This will prompt the user for a .nuspec, project, or .nupkg file if one is not found in the same directory as the script, as well as for any other input that is required. 97 | This assumes that you are currently in the same directory as the New-NuGetPackage.ps1 script, since a relative path is supplied. 98 | 99 | .EXAMPLE 100 | & "C:\Some Folder\New-NuGetPackage.ps1" -NuSpecFilePath ".\Some Folder\SomeNuSpecFile.nuspec" -Verbose 101 | 102 | Create a new package from the SomeNuSpecFile.nuspec file. 103 | This can be ran from any directory since an absolute path to the New-NuGetPackage.ps1 script is supplied. 104 | Additional information will be displayed about the operations being performed because the -Verbose switch was supplied. 105 | 106 | .EXAMPLE 107 | & .\New-NuGetPackage.ps1 -ProjectFilePath "C:\Some Folder\TestProject.csproj" -VersionNumber "1.1" -ReleaseNotes "Version 1.1 contains many bug fixes." 108 | 109 | Create a new package from the TestProject.csproj file. 110 | Because the VersionNumber and ReleaseNotes parameters are provided, the user will not be prompted for them. 111 | If "C:\Some Folder\TestProject.nuspec" exists, it will automatically be picked up and used when creating the package; if it contained a version number or release notes, they will be overwritten with the ones provided. 112 | 113 | .EXAMPLE 114 | & .\New-NuGetPackage.ps1 -ProjectFilePath "C:\Some Folder\TestProject.csproj" -PackOptions "-Build -OutputDirectory ""C:\Output""" -UsePowerShellPrompts 115 | 116 | Create a new package from the TestProject.csproj file, building the project before packing it and saving the package in "C:\Output". 117 | Because the UsePowerShellPrompts parameter was provided, all prompts will be made via the PowerShell console instead of GUI popups. 118 | 119 | .EXAMPLE 120 | & .\New-NuGetPackage.ps1 -NuSpecFilePath "C:\Some Folder\SomeNuSpecFile.nuspec" -NoPrompt 121 | 122 | Create a new package from SomeNuSpecFile.nuspec without prompting the user for anything, so the existing version number and release notes in the .nuspec file will be used. 123 | 124 | .EXAMPLE 125 | & .\New-NuGetPackage.ps1 -NuSpecFilePath ".\Some Folder\SomeNuSpecFile.nuspec" -VersionNumber "9.9.9.9" -DoNotUpdateNuSpecFile 126 | 127 | Create a new package with version number "9.9.9.9" from SomeNuSpecFile.nuspec without saving the changes to the file. 128 | 129 | .EXAMPLE 130 | & .\New-NuGetPackage.ps1 -NuSpecFilePath "C:\Some Folder\SomeNuSpecFile.nuspec" -PushPackageToNuGetGallery -PushOptions "-Source ""http://my.server.com/MyNuGetGallery"" -ApiKey ""EAE1E980-5ECB-4453-9623-F0A0250E3A57""" 131 | 132 | Create a new package from SomeNuSpecFile.nuspec and push it to a custom NuGet gallery using the user's unique Api Key. 133 | 134 | .EXAMPLE 135 | & .\New-NuGetPackage.ps1 -NuSpecFilePath "C:\Some Folder\SomeNuSpecFile.nuspec" -NuGetExecutableFilePath "C:\Utils\NuGet.exe" 136 | 137 | Create a new package from SomeNuSpecFile.nuspec by specifying the path to the NuGet executable (required when NuGet.exe is not in the user's PATH). 138 | 139 | .EXAMPLE 140 | & New-NuGetPackage.ps1 -PackageFilePath "C:\Some Folder\MyPackage.nupkg" 141 | 142 | Push the existing "MyPackage.nupkg" file to the NuGet gallery. 143 | User will be prompted to confirm that they want to push the package; to avoid this prompt supply the -PushPackageToNuGetGallery switch. 144 | 145 | .EXAMPLE 146 | & .\New-NuGetPackage.ps1 -NoPromptForInputOnError -UpdateNuGetExecutable 147 | 148 | Create a new package or push an existing package by auto-finding the .nuspec, project, or .nupkg file to use, and prompting for one if none are found. 149 | Will not prompt the user for input before exitting the script when an error occurs. 150 | 151 | .OUTPUTS 152 | Returns the full path to the NuGet package that was created. 153 | If a NuGet package was not required to be created (e.g. you were just pushing an existing package), then nothing is returned. 154 | Use the -Verbose switch to see more detailed information about the operations performed. 155 | 156 | .LINK 157 | Project home: https://newnugetpackage.codeplex.com 158 | 159 | .NOTES 160 | Author: Daniel Schroeder 161 | Version: 1.5.11 162 | 163 | This script is designed to be called from PowerShell or ran directly from Windows Explorer. 164 | If this script is ran without the $NuSpecFilePath, $ProjectFilePath, and $PackageFilePath parameters, it will automatically search for a .nuspec, project, or package file in the 165 | same directory as the script and use it if one is found. If none or more than one are found, the user will be prompted to specify the file to use. 166 | #> 167 | [CmdletBinding(DefaultParameterSetName="PackUsingNuSpec")] 168 | param 169 | ( 170 | [parameter(Position=1,Mandatory=$false,ParameterSetName="PackUsingNuSpec")] 171 | [ValidateScript({Test-Path $_ -PathType Leaf})] 172 | [string] $NuSpecFilePath, 173 | 174 | [parameter(Position=1,Mandatory=$false,ParameterSetName="PackUsingProject")] 175 | [ValidateScript({Test-Path $_ -PathType Leaf})] 176 | [string] $ProjectFilePath, 177 | 178 | [parameter(Position=1,Mandatory=$false,ParameterSetName="PushExistingPackage")] 179 | [ValidateScript({Test-Path $_ -PathType Leaf})] 180 | [string] $PackageFilePath, 181 | 182 | [parameter(Position=2,Mandatory=$false,HelpMessage="The new version number to use for the NuGet Package.",ParameterSetName="PackUsingNuSpec")] 183 | [parameter(Position=2,Mandatory=$false,HelpMessage="The new version number to use for the NuGet Package.",ParameterSetName="PackUsingProject")] 184 | [ValidatePattern('(?i)(^\d+(\.\d+){1,3}(-[a-zA-Z0-9\-\.\+]+)?$)|(^(\$version\$)$)|(^$)')] # This validation is duplicated in the Update-NuSpecFile function, so update it in both places. This regex does not represent Sematic Versioning, but the versioning that NuGet.exe allows. 185 | [Alias("Version")] 186 | [Alias("V")] 187 | [string] $VersionNumber, 188 | 189 | [parameter(ParameterSetName="PackUsingNuSpec")] 190 | [parameter(ParameterSetName="PackUsingProject")] 191 | [Alias("Notes")] 192 | [string] $ReleaseNotes, 193 | 194 | [parameter(ParameterSetName="PackUsingNuSpec")] 195 | [parameter(ParameterSetName="PackUsingProject")] 196 | [Alias("PO")] 197 | [string] $PackOptions = "-Build", # Build projects by default to make sure the files to pack exist. 198 | 199 | [Alias("Push")] 200 | [switch] $PushPackageToNuGetGallery, 201 | 202 | [string] $PushOptions, 203 | 204 | [Alias("DPAP")] 205 | [switch] $DeletePackageAfterPush, 206 | 207 | [Alias("NP")] 208 | [switch] $NoPrompt, 209 | 210 | [Alias("NPEOE")] 211 | [switch] $NoPromptExceptOnError, 212 | 213 | [parameter(ParameterSetName="PackUsingNuSpec")] 214 | [parameter(ParameterSetName="PackUsingProject")] 215 | [Alias("NPFVN")] 216 | [switch] $NoPromptForVersionNumber, 217 | 218 | [parameter(ParameterSetName="PackUsingNuSpec")] 219 | [parameter(ParameterSetName="PackUsingProject")] 220 | [Alias("NPFRN")] 221 | [switch] $NoPromptForReleaseNotes, 222 | 223 | [Alias("NPFPPTNG")] 224 | [switch] $NoPromptForPushPackageToNuGetGallery, 225 | 226 | [Alias("NPFIOE")] 227 | [switch] $NoPromptForInputOnError, 228 | 229 | [Alias("UPSP")] 230 | [switch] $UsePowerShellPrompts, 231 | 232 | [parameter(ParameterSetName="PackUsingNuSpec")] 233 | [parameter(ParameterSetName="PackUsingProject")] 234 | [Alias("NoUpdate")] 235 | [switch] $DoNotUpdateNuSpecFile, 236 | 237 | [Alias("NuGet")] 238 | [string] $NuGetExecutableFilePath, 239 | 240 | [Alias("UNE")] 241 | [switch] $UpdateNuGetExecutable, 242 | 243 | [Alias("TF")] 244 | [string] $TfExecutableFilePath 245 | ) 246 | 247 | # Turn on Strict Mode to help catch syntax-related errors. 248 | # This must come after a script's/function's param section. 249 | # Forces a function to be the first non-comment code to appear in a PowerShell Module. 250 | Set-StrictMode -Version Latest 251 | 252 | # Default the ParameterSet variables that may not have been set depending on which parameter set is being used. This is required for PowerShell v2.0 compatibility. 253 | if (!(Test-Path Variable:Private:NuSpecFilePath)) { $NuSpecFilePath = $null } 254 | if (!(Test-Path Variable:Private:ProjectFilePath)) { $ProjectFilePath = $null } 255 | if (!(Test-Path Variable:Private:PackageFilePath)) { $PackageFilePath = $null } 256 | if (!(Test-Path Variable:Private:VersionNumber)) { $VersionNumber = $null } 257 | if (!(Test-Path Variable:Private:ReleaseNotes)) { $ReleaseNotes = $null } 258 | if (!(Test-Path Variable:Private:PackOptions)) { $PackOptions = $null } 259 | if (!(Test-Path Variable:Private:NoPromptForVersionNumber)) { $NoPromptForVersionNumber = $false } 260 | if (!(Test-Path Variable:Private:NoPromptForReleaseNotes)) { $NoPromptForReleaseNotes = $false } 261 | if (!(Test-Path Variable:Private:DoNotUpdateNuSpecFile)) { $DoNotUpdateNuSpecFile = $false } 262 | 263 | 264 | #========================================================== 265 | # Define any necessary global variables, such as file paths. 266 | #========================================================== 267 | 268 | # Import any necessary assemblies. 269 | Add-Type -AssemblyName System.Windows.Forms 270 | Add-Type -AssemblyName Microsoft.VisualBasic 271 | 272 | # Get the directory that this script is in. 273 | $THIS_SCRIPTS_DIRECTORY_PATH = Split-Path $script:MyInvocation.MyCommand.Path 274 | 275 | # The list of project type extensions that NuGet supports packing. 276 | $VALID_NUGET_PROJECT_TYPE_EXTENSIONS_ARRAY = @(".csproj", ".vbproj", ".fsproj") 277 | 278 | $VALID_NUGET_PROJECT_TYPE_EXTENSIONS_WITH_WILDCARD_ARRAY = @() 279 | foreach ($extension in $VALID_NUGET_PROJECT_TYPE_EXTENSIONS_ARRAY) 280 | { 281 | $VALID_NUGET_PROJECT_TYPE_EXTENSIONS_WITH_WILDCARD_ARRAY += "*$extension" 282 | } 283 | 284 | # The directory to put the NuGet package into if one is not supplied. 285 | $DEFAULT_DIRECTORY_TO_PUT_NUGET_PACKAGES_IN = "New-NuGetPackages" 286 | 287 | # The file path where the API keys are saved. 288 | $NUGET_CONFIG_FILE_PATH = Join-Path $env:APPDATA "NuGet\NuGet.config" 289 | 290 | # The default NuGet source to push to when one is not explicitly provided. 291 | $DEFAULT_NUGET_SOURCE_TO_PUSH_TO = "https://www.nuget.org" 292 | 293 | #========================================================== 294 | # Strings to look for in console app output. 295 | # If running in a non-english language, these strings will need to be changed to the strings returned by the console apps when running in the non-english language. 296 | #========================================================== 297 | 298 | # TF.exe output strings. 299 | $TF_EXE_NO_WORKING_FOLDER_MAPPING_ERROR_MESSAGE = 'There is no working folder mapping for' 300 | $TF_EXE_NO_PENDING_CHANGES_MESSAGE = 'There are no pending changes.' 301 | $TF_EXE_KEYWORD_IN_PENDING_CHANGES_MESSAGE = 'change\(s\)' # Escape regular expression characters. 302 | 303 | # NuGet.exe output strings. 304 | $NUGET_EXE_VERSION_NUMBER_REGEX = [regex] "(?i)(NuGet Version: (?\d+\.\d+\.\d+\.\d+).)" 305 | $NUGET_EXE_SUCCESSFULLY_CREATED_PACKAGE_MESSAGE_REGEX = [regex] "(?i)(Successfully created package '(?.*?)'.)" 306 | $NUGET_EXE_SUCCESSFULLY_PUSHED_PACKAGE_MESSAGE = 'Your package was pushed.' 307 | $NUGET_EXE_SUCCESSFULLY_SAVED_API_KEY_MESSAGE = "The API Key '{0}' was saved for '{1}'." 308 | $NUGET_EXE_SUCCESSFULLY_UPDATED_TO_NEW_VERSION = 'Update successful.' 309 | 310 | #========================================================== 311 | # Define functions used by the script. 312 | #========================================================== 313 | 314 | # Catch any exceptions thrown, display the error message, wait for input if appropriate, and then stop the script. 315 | trap [Exception] 316 | { 317 | $errorMessage = $_ 318 | Write-Host "An error occurred while running New-NuGetPackage script:`n$errorMessage`n" -Foreground Red 319 | 320 | if (!$NoPromptForInputOnError) 321 | { 322 | # If we should prompt directly from PowerShell. 323 | if ($UsePowerShellPrompts) 324 | { 325 | Write-Host "Press any key to continue ..." 326 | $x = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp") 327 | } 328 | # Else use a nice GUI prompt. 329 | else 330 | { 331 | $VersionNumber = Read-MessageBoxDialog -Message $errorMessage -WindowTitle "Error Occurred Running New-NuGetPackage Script" -Buttons OK -Icon Error 332 | } 333 | } 334 | break 335 | } 336 | 337 | # Function to return the path to backup the NuSpec file to if needed. 338 | function Get-NuSpecBackupFilePath { return "$NuSpecFilePath.backup" } 339 | 340 | # PowerShell v2.0 compatible version of [string]::IsNullOrWhitespace. 341 | function Test-StringIsNullOrWhitespace([string] $string) 342 | { 343 | if ($string -ne $null) { $string = $string.Trim() } 344 | return [string]::IsNullOrEmpty($string) 345 | } 346 | 347 | # Function to update the $NuSpecFilePath (.nuspec file) with the appropriate information before using it to create the NuGet package. 348 | function Update-NuSpecFile 349 | { 350 | Write-Verbose "Starting process to update the nuspec file '$NuSpecFilePath'..." 351 | 352 | # If we don't have a NuSpec file to update, throw an error that something went wrong. 353 | if (!(Test-Path $NuSpecFilePath)) 354 | { 355 | throw "The Update-NuSpecFile function was called with an invalid NuSpecFilePath; this should not happen. There must be a bug in this script." 356 | } 357 | 358 | # Validate that the NuSpec file is a valid xml file. 359 | try 360 | { 361 | $nuSpecXml = New-Object System.Xml.XmlDocument 362 | $nuSpecXml.Load($NuSpecFilePath) # Will throw an exception if it is unable to load the xml properly. 363 | $nuSpecXml = $null # Release the memory. 364 | } 365 | catch 366 | { 367 | throw ("An error occurred loading the nuspec xml file '{0}': {1}" -f $NuSpecFilePath, $_.Exception.Message) 368 | } 369 | 370 | # Get the NuSpec file contents and Last Write Time before we make any changes to it, so we can determine if we did in fact make changes to it later (and undo the checkout from TFS if we didn't). 371 | $script:nuSpecFileContentsBeforeCheckout = [System.IO.File]::ReadAllText($NuSpecFilePath) 372 | $script:nuSpecLastWriteTimeBeforeCheckout = [System.IO.File]::GetLastWriteTime($NuSpecFilePath) 373 | 374 | # Try and check the file out of TFS. 375 | $script:nuSpecFileWasAlreadyCheckedOut = Tfs-IsItemCheckedOut -Path $NuSpecFilePath 376 | if ($script:nuSpecFileWasAlreadyCheckedOut -eq $false) { Tfs-Checkout -Path $NuSpecFilePath } 377 | 378 | # If we shouldn't update to the .nuspec file permanently, create a backup that we can restore from after. 379 | if ($DoNotUpdateNuSpecFile) 380 | { 381 | Copy-Item -Path $NuSpecFilePath -Destination (Get-NuSpecBackupFilePath) -Force 382 | } 383 | 384 | # Get the current version number from the .nuspec file. 385 | $currentVersionNumber = Get-NuSpecVersionNumber -NuSpecFilePath $NuSpecFilePath 386 | 387 | # If an explicit Version Number was not provided, prompt for it. 388 | if (Test-StringIsNullOrWhitespace $VersionNumber) 389 | { 390 | # If we shouldn't prompt for a version number, just use the existing one from the NuSpec file (if it exists). 391 | if ($NoPromptForVersionNumber) 392 | { 393 | $VersionNumber = $currentVersionNumber 394 | } 395 | # Else prompt the user for the version number to use. 396 | else 397 | { 398 | $promptMessage = 'Enter the NuGet package version number to use (x.x[.x.x] or $version$ if packing a project file)' 399 | 400 | # If we should prompt directly from PowerShell. 401 | if ($UsePowerShellPrompts) 402 | { 403 | $VersionNumber = Read-Host "$promptMessage. Current value in the .nuspec file is:`n$currentVersionNumber`n" 404 | } 405 | # Else use a nice GUI prompt. 406 | else 407 | { 408 | $VersionNumber = Read-InputBoxDialog -Message "$promptMessage`:" -WindowTitle "NuGet Package Version Number" -DefaultText $currentVersionNumber 409 | } 410 | } 411 | 412 | # The script's parameter validation does not seem to be enforced (probably because this is inside a function), so re-enforce it here. 413 | $rxVersionNumberValidation = [regex] '(?i)(^\d+(\.\d+){1,3}(-[a-zA-Z0-9\-\.\+]+)?$)|(^(\$version\$)$)|(^$)' # This validation is duplicated in the script's $Version parameter validation, so update it in both places. This regex does not represent Sematic Versioning, but the versioning that NuGet.exe allows. 414 | 415 | # If the user cancelled the prompt or did not provide a valid version number, exit the script. 416 | if ((Test-StringIsNullOrWhitespace $VersionNumber) -or !$rxVersionNumberValidation.IsMatch($VersionNumber)) 417 | { 418 | throw "A valid version number to use for the NuGet package was not provided, so exiting script. The version number provided was '$VersionNumber', which does not conform to the Semantic Versioning guidelines specified at http://semver.org." 419 | } 420 | } 421 | 422 | # Insert the given version number into the .nuspec file, if it is different. 423 | if ($currentVersionNumber -ne $VersionNumber) 424 | { 425 | Set-NuSpecVersionNumber -NuSpecFilePath $NuSpecFilePath -NewVersionNumber $VersionNumber 426 | } 427 | 428 | # Get the current release notes from the .nuspec file. 429 | $currentReleaseNotes = Get-NuSpecReleaseNotes -NuSpecFilePath $NuSpecFilePath 430 | 431 | # If the Release Notes were not provided, prompt for them. 432 | if (Test-StringIsNullOrWhitespace $ReleaseNotes) 433 | { 434 | # If we shouldn't prompt for the release notes, just use the existing ones from the NuSpec file (if it exists). 435 | if ($NoPromptForReleaseNotes) 436 | { 437 | $ReleaseNotes = $currentReleaseNotes 438 | } 439 | # Else prompt the user for the Release Notes to add to the .nuspec file. 440 | else 441 | { 442 | $promptMessage = "Please enter the release notes to include in the new NuGet package" 443 | 444 | # If we should prompt directly from PowerShell. 445 | if ($UsePowerShellPrompts) 446 | { 447 | $ReleaseNotes = Read-Host "$promptMessage. Current value in the .nuspec file is:`n$currentReleaseNotes`n" 448 | } 449 | # Else use a nice GUI prompt. 450 | else 451 | { 452 | $ReleaseNotes = Read-MultiLineInputBoxDialog -Message "$promptMessage`:" -WindowTitle "Enter Release Notes For New Package" -DefaultText $currentReleaseNotes 453 | } 454 | 455 | # If the user cancelled the release notes prompt, exit the script. 456 | if ($ReleaseNotes -eq $null) 457 | { 458 | throw "User cancelled the Release Notes prompt, so exiting script." 459 | } 460 | } 461 | } 462 | 463 | # Insert the given Release Notes into the .nuspec file if some were provided, and they are different than the current ones. 464 | if ($currentReleaseNotes -ne $ReleaseNotes) 465 | { 466 | Set-NuSpecReleaseNotes -NuSpecFilePath $NuSpecFilePath -NewReleaseNotes $ReleaseNotes 467 | } 468 | 469 | Write-Verbose "Finished process to update the nuspec file '$NuSpecFilePath'." 470 | } 471 | 472 | function Get-NuSpecVersionNumber([parameter(Position=1,Mandatory=$true)][ValidateScript({Test-Path $_ -PathType Leaf})][string] $NuSpecFilePath) 473 | { 474 | # Read in the file contents and return the version element's value. 475 | $fileContents = New-Object System.Xml.XmlDocument 476 | $fileContents.Load($NuSpecFilePath) 477 | return Get-XmlElementsTextValue -XmlDocument $fileContents -ElementPath "package.metadata.version" 478 | } 479 | 480 | function Set-NuSpecVersionNumber([parameter(Position=1,Mandatory=$true)][ValidateScript({Test-Path $_ -PathType Leaf})][string] $NuSpecFilePath, [parameter(Position=2,Mandatory=$true)][string] $NewVersionNumber) 481 | { 482 | # Read in the file contents, update the version element's value, and save the file. 483 | $fileContents = New-Object System.Xml.XmlDocument 484 | $fileContents.Load($NuSpecFilePath) 485 | Set-XmlElementsTextValue -XmlDocument $fileContents -ElementPath "package.metadata.version" -TextValue $NewVersionNumber 486 | $fileContents.Save($NuSpecFilePath) 487 | } 488 | 489 | function Get-NuSpecReleaseNotes([parameter(Position=1,Mandatory=$true)][ValidateScript({Test-Path $_ -PathType Leaf})][string] $NuSpecFilePath) 490 | { 491 | # Read in the file contents and return the version element's value. 492 | $fileContents = New-Object System.Xml.XmlDocument 493 | $fileContents.Load($NuSpecFilePath) 494 | return Get-XmlElementsTextValue -XmlDocument $fileContents -ElementPath "package.metadata.releaseNotes" 495 | } 496 | 497 | function Set-NuSpecReleaseNotes([parameter(Position=1,Mandatory=$true)][ValidateScript({Test-Path $_ -PathType Leaf})][string] $NuSpecFilePath, [parameter(Position=2)][string] $NewReleaseNotes) 498 | { 499 | # Read in the file contents, update the version element's value, and save the file. 500 | $fileContents = New-Object System.Xml.XmlDocument 501 | $fileContents.Load($NuSpecFilePath) 502 | Set-XmlElementsTextValue -XmlDocument $fileContents -ElementPath "package.metadata.releaseNotes" -TextValue $NewReleaseNotes 503 | $fileContents.Save($NuSpecFilePath) 504 | } 505 | 506 | function Get-XmlNamespaceManager([xml]$XmlDocument, [string]$NamespaceURI = "") 507 | { 508 | # If a Namespace URI was not given, use the Xml document's default namespace. 509 | if ([string]::IsNullOrEmpty($NamespaceURI)) { $NamespaceURI = $XmlDocument.DocumentElement.NamespaceURI } 510 | 511 | # In order for SelectSingleNode() to actually work, we need to use the fully qualified node path along with an Xml Namespace Manager, so set them up. 512 | [System.Xml.XmlNamespaceManager]$xmlNsManager = New-Object System.Xml.XmlNamespaceManager($XmlDocument.NameTable) 513 | $xmlNsManager.AddNamespace("ns", $NamespaceURI) 514 | return ,$xmlNsManager # Need to put the comma before the variable name so that PowerShell doesn't convert it into an Object[]. 515 | } 516 | 517 | function Get-FullyQualifiedXmlNodePath([string]$NodePath, [string]$NodeSeparatorCharacter = '.') 518 | { 519 | return "/ns:$($NodePath.Replace($($NodeSeparatorCharacter), '/ns:'))" 520 | } 521 | 522 | function Get-XmlNode([xml]$XmlDocument, [string]$NodePath, [string]$NamespaceURI = "", [string]$NodeSeparatorCharacter = '.') 523 | { 524 | $xmlNsManager = Get-XmlNamespaceManager -XmlDocument $XmlDocument -NamespaceURI $NamespaceURI 525 | [string]$fullyQualifiedNodePath = Get-FullyQualifiedXmlNodePath -NodePath $NodePath -NodeSeparatorCharacter $NodeSeparatorCharacter 526 | 527 | # Try and get the node, then return it. Returns $null if the node was not found. 528 | $node = $XmlDocument.SelectSingleNode($fullyQualifiedNodePath, $xmlNsManager) 529 | return $node 530 | } 531 | 532 | function Get-XmlNodes([xml]$XmlDocument, [string]$NodePath, [string]$NamespaceURI = "", [string]$NodeSeparatorCharacter = '.') 533 | { 534 | $xmlNsManager = Get-XmlNamespaceManager -XmlDocument $XmlDocument -NamespaceURI $NamespaceURI 535 | [string]$fullyQualifiedNodePath = Get-FullyQualifiedXmlNodePath -NodePath $NodePath -NodeSeparatorCharacter $NodeSeparatorCharacter 536 | 537 | # Try and get the nodes, then return them. Returns $null if no nodes were found. 538 | $nodes = $XmlDocument.SelectNodes($fullyQualifiedNodePath, $xmlNsManager) 539 | return $nodes 540 | } 541 | 542 | function Get-XmlElementsTextValue([xml]$XmlDocument, [string]$ElementPath, [string]$NamespaceURI = "", [string]$NodeSeparatorCharacter = '.') 543 | { 544 | # Try and get the node. 545 | $node = Get-XmlNode -XmlDocument $XmlDocument -NodePath $ElementPath -NamespaceURI $NamespaceURI -NodeSeparatorCharacter $NodeSeparatorCharacter 546 | 547 | # If the node already exists, return its value, otherwise return null. 548 | if ($node) { return $node.InnerText } else { return $null } 549 | } 550 | 551 | function Set-XmlElementsTextValue([xml]$XmlDocument, [string]$ElementPath, [string]$TextValue, [string]$NamespaceURI = "", [string]$NodeSeparatorCharacter = '.') 552 | { 553 | # Try and get the node. 554 | $node = Get-XmlNode -XmlDocument $XmlDocument -NodePath $ElementPath -NamespaceURI $NamespaceURI -NodeSeparatorCharacter $NodeSeparatorCharacter 555 | 556 | # If the node already exists, update its value. 557 | if ($node) 558 | { 559 | $node.InnerText = $TextValue 560 | } 561 | # Else the node doesn't exist yet, so create it with the given value. 562 | else 563 | { 564 | # Create the new element with the given value. 565 | $elementName = $ElementPath.Substring($ElementPath.LastIndexOf($NodeSeparatorCharacter) + 1) 566 | $element = $XmlDocument.CreateElement($elementName, $XmlDocument.DocumentElement.NamespaceURI) 567 | $textNode = $XmlDocument.CreateTextNode($TextValue) 568 | $element.AppendChild($textNode) > $null 569 | 570 | # Try and get the parent node. 571 | $parentNodePath = $ElementPath.Substring(0, $ElementPath.LastIndexOf($NodeSeparatorCharacter)) 572 | $parentNode = Get-XmlNode -XmlDocument $XmlDocument -NodePath $parentNodePath -NamespaceURI $NamespaceURI -NodeSeparatorCharacter $NodeSeparatorCharacter 573 | 574 | if ($parentNode) 575 | { 576 | $parentNode.AppendChild($element) > $null 577 | } 578 | else 579 | { 580 | throw "$parentNodePath does not exist in the xml." 581 | } 582 | } 583 | } 584 | 585 | # Show an Open File Dialog and return the file selected by the user. 586 | function Read-OpenFileDialog([string]$WindowTitle, [string]$InitialDirectory, [string]$Filter = "All files (*.*)|*.*", [switch]$AllowMultiSelect) 587 | { 588 | Add-Type -AssemblyName System.Windows.Forms 589 | $openFileDialog = New-Object System.Windows.Forms.OpenFileDialog 590 | $openFileDialog.Title = $WindowTitle 591 | if (!(Test-StringIsNullOrWhitespace $InitialDirectory)) { $openFileDialog.InitialDirectory = $InitialDirectory } 592 | $openFileDialog.Filter = $Filter 593 | if ($AllowMultiSelect) { $openFileDialog.MultiSelect = $true } 594 | $openFileDialog.ShowHelp = $true # Without this line the ShowDialog() function may hang depending on system configuration and running from console vs. ISE. 595 | $openFileDialog.ShowDialog() > $null 596 | if ($AllowMultiSelect) { return $openFileDialog.Filenames } else { return $openFileDialog.Filename } 597 | } 598 | 599 | # Show message box popup and return the button clicked by the user. 600 | function Read-MessageBoxDialog([string]$Message, [string]$WindowTitle, [System.Windows.Forms.MessageBoxButtons]$Buttons = [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]$Icon = [System.Windows.Forms.MessageBoxIcon]::None) 601 | { 602 | Add-Type -AssemblyName System.Windows.Forms 603 | return [System.Windows.Forms.MessageBox]::Show($Message, $WindowTitle, $Buttons, $Icon) 604 | } 605 | 606 | # Show input box popup and return the value entered by the user. 607 | function Read-InputBoxDialog([string]$Message, [string]$WindowTitle, [string]$DefaultText) 608 | { 609 | Add-Type -AssemblyName Microsoft.VisualBasic 610 | return [Microsoft.VisualBasic.Interaction]::InputBox($Message, $WindowTitle, $DefaultText) 611 | } 612 | 613 | function Read-MultiLineInputBoxDialog([string]$Message, [string]$WindowTitle, [string]$DefaultText) 614 | { 615 | <# 616 | .SYNOPSIS 617 | Prompts the user with a multi-line input box and returns the text they enter, or null if they cancelled the prompt. 618 | 619 | .DESCRIPTION 620 | Prompts the user with a multi-line input box and returns the text they enter, or null if they cancelled the prompt. 621 | 622 | .PARAMETER Message 623 | The message to display to the user explaining what text we are asking them to enter. 624 | 625 | .PARAMETER WindowTitle 626 | The text to display on the prompt window's title. 627 | 628 | .PARAMETER DefaultText 629 | The default text to show in the input box. 630 | 631 | .EXAMPLE 632 | $userText = Read-MultiLineInputDialog "Input some text please:" "Get User's Input" 633 | 634 | Shows how to create a simple prompt to get mutli-line input from a user. 635 | 636 | .EXAMPLE 637 | # Setup the default multi-line address to fill the input box with. 638 | $defaultAddress = @' 639 | John Doe 640 | 123 St. 641 | Some Town, SK, Canada 642 | A1B 2C3 643 | '@ 644 | 645 | $address = Read-MultiLineInputDialog "Please enter your full address, including name, street, city, and postal code:" "Get User's Address" $defaultAddress 646 | if ($address -eq $null) 647 | { 648 | Write-Error "You pressed the Cancel button on the multi-line input box." 649 | } 650 | 651 | Prompts the user for their address and stores it in a variable, pre-filling the input box with a default multi-line address. 652 | If the user pressed the Cancel button an error is written to the console. 653 | 654 | .EXAMPLE 655 | $inputText = Read-MultiLineInputDialog -Message "If you have a really long message you can break it apart`nover two lines with the powershell newline character:" -WindowTitle "Window Title" -DefaultText "Default text for the input box." 656 | 657 | Shows how to break the second parameter (Message) up onto two lines using the powershell newline character (`n). 658 | If you break the message up into more than two lines the extra lines will be hidden behind or show ontop of the TextBox. 659 | 660 | .NOTES 661 | Name: Show-MultiLineInputDialog 662 | Author: Daniel Schroeder (originally based on the code shown at http://technet.microsoft.com/en-us/library/ff730941.aspx) 663 | Version: 1.0 664 | #> 665 | Add-Type -AssemblyName System.Drawing 666 | Add-Type -AssemblyName System.Windows.Forms 667 | 668 | # Create the Label. 669 | $label = New-Object System.Windows.Forms.Label 670 | $label.Location = New-Object System.Drawing.Size(10,10) 671 | $label.Size = New-Object System.Drawing.Size(280,20) 672 | $label.AutoSize = $true 673 | $label.Text = $Message 674 | 675 | # Create the TextBox used to capture the user's text. 676 | $textBox = New-Object System.Windows.Forms.TextBox 677 | $textBox.Location = New-Object System.Drawing.Size(10,40) 678 | $textBox.Size = New-Object System.Drawing.Size(575,200) 679 | $textBox.AcceptsReturn = $true 680 | $textBox.AcceptsTab = $false 681 | $textBox.Multiline = $true 682 | $textBox.ScrollBars = 'Both' 683 | $textBox.Text = $DefaultText 684 | 685 | # Create the OK button. 686 | $okButton = New-Object System.Windows.Forms.Button 687 | $okButton.Location = New-Object System.Drawing.Size(415,250) 688 | $okButton.Size = New-Object System.Drawing.Size(75,25) 689 | $okButton.Text = "OK" 690 | $okButton.Add_Click({ $form.Tag = $textBox.Text; $form.Close() }) 691 | 692 | # Create the Cancel button. 693 | $cancelButton = New-Object System.Windows.Forms.Button 694 | $cancelButton.Location = New-Object System.Drawing.Size(510,250) 695 | $cancelButton.Size = New-Object System.Drawing.Size(75,25) 696 | $cancelButton.Text = "Cancel" 697 | $cancelButton.Add_Click({ $form.Tag = $null; $form.Close() }) 698 | 699 | # Create the form. 700 | $form = New-Object System.Windows.Forms.Form 701 | $form.Text = $WindowTitle 702 | $form.Size = New-Object System.Drawing.Size(610,320) 703 | $form.FormBorderStyle = 'FixedSingle' 704 | $form.StartPosition = "CenterScreen" 705 | $form.AutoSizeMode = 'GrowAndShrink' 706 | $form.Topmost = $True 707 | $form.AcceptButton = $okButton 708 | $form.CancelButton = $cancelButton 709 | $form.ShowInTaskbar = $true 710 | 711 | # Add all of the controls to the form. 712 | $form.Controls.Add($label) 713 | $form.Controls.Add($textBox) 714 | $form.Controls.Add($okButton) 715 | $form.Controls.Add($cancelButton) 716 | 717 | # Initialize and show the form. 718 | $form.Add_Shown({$form.Activate()}) 719 | $form.ShowDialog() > $null # Trash the text of the button that was clicked. 720 | 721 | # Return the text that the user entered. 722 | return $form.Tag 723 | } 724 | 725 | function Get-TfExecutablePath 726 | { 727 | # If we already have the TF.exe path and it exists, just return it. 728 | if ($TfExecutableFilePath -and (!(Test-StringIsNullOrWhitespace $TfExecutableFilePath)) -and (Test-Path -Path $TfExecutableFilePath -PathType Leaf)) 729 | { 730 | return $TfExecutableFilePath 731 | } 732 | 733 | # Get the latest visual studio IDE path (up to VS 2015, as 2017+ stopped adding an environmental variable path). 734 | # We still try method rather than just using the VSSetup module simply for performance reasons. 735 | $vsIdePath = [string]::Empty 736 | $vsCommonToolsPaths = @($env:VS140COMNTOOLS,$env:VS120COMNTOOLS,$env:VS110COMNTOOLS,$env:VS100COMNTOOLS) 737 | $vsCommonToolsPaths = @($VsCommonToolsPaths | Where-Object {$_ -ne $null}) 738 | 739 | # Loop through each version from largest to smallest. 740 | foreach ($vsCommonToolsPath in $vsCommonToolsPaths) 741 | { 742 | if ($null -ne $vsCommonToolsPath) 743 | { 744 | $vsIdePath = "${vsCommonToolsPath}..\IDE\" 745 | break 746 | } 747 | } 748 | $TfExecutableFilePath = "${vsIdePath}TF.exe" 749 | 750 | # If we still don't have a valid path yet, try getting it using the VSSetup module. 751 | if (!(Test-Path -Path $TfExecutableFilePath -PathType Leaf)) 752 | { 753 | # Try and install the VSSetup module if needed. 754 | [bool] $vsSetupModuleIsInstalled = $null -ne (Get-Command -Name Get-VSSetupInstance -ErrorAction SilentlyContinue) 755 | if (!$vsSetupModuleIsInstalled) 756 | { 757 | [bool] $packageProviderCmdletsAreAvailable = $null -eq (Get-Command -Name Install-PackageProvider -ErrorAction SilentlyContinue) 758 | if ($packageProviderCmdletsAreAvailable) 759 | { 760 | [bool] $nuGetPackageProviderIsInstalled = $null -eq (Get-PackageProvider -Name NuGet -ErrorAction SilentlyContinue) 761 | if (!$nuGetPackageProviderIsInstalled) 762 | { 763 | Write-Verbose "Installing the NuGet package provider in order to obtain the VSSetup module..." 764 | Install-PackageProvider -Name NuGet -Force 765 | } 766 | 767 | Write-Verbose "Installing the VSSetup module in order to determine TF.exe path..." -Verbose 768 | Install-Module VSSetup -Scope CurrentUser -Force 769 | } 770 | else 771 | { 772 | Write-Verbose "The PowerShell commands to retrieve the VSSetup module are not available, so we will not be able to determine the path to TF.exe. Likely the version of PowerShell installed is too low." -Verbose 773 | } 774 | } 775 | 776 | [bool] $vsSetupModuleIsInstalled = $null -ne (Get-Command -Name Get-VSSetupInstance -ErrorAction SilentlyContinue) 777 | if ($vsSetupModuleIsInstalled) 778 | { 779 | [string] $visualStudioInstallationPath = (Get-VSSetupInstance | Select-VSSetupInstance -Latest -Require Microsoft.Component.MSBuild).InstallationPath 780 | $TfExecutableFilePath = (Get-ChildItem $visualStudioInstallationPath -Recurse -Filter "TF.exe" | Select-Object -First 1).FullName 781 | } 782 | } 783 | 784 | # If we still don't have a valid path, write a warning about and return an empty string. 785 | if (!(Test-Path -Path $TfExecutableFilePath -PathType Leaf)) 786 | { 787 | Write-Warning "Unable to locate TF.exe." 788 | return [string]::Empty 789 | } 790 | 791 | # Return the absolute path to TF.exe. 792 | $TfExecutableFilePath = Resolve-Path $TfExecutableFilePath 793 | return $TfExecutableFilePath 794 | } 795 | 796 | function Tfs-Checkout 797 | { 798 | [CmdletBinding()] 799 | param 800 | ( 801 | [Parameter(Mandatory=$true, Position=0, HelpMessage="The local path to the file or folder to checkout from TFS source control.")] 802 | [string]$Path, 803 | 804 | [switch]$Recursive 805 | ) 806 | 807 | $tfPath = Get-TfExecutablePath 808 | 809 | # If we couldn't find TF.exe, just return without doing anything. 810 | if (Test-StringIsNullOrWhitespace $tfPath) 811 | { 812 | Write-Warning "Unable to locate TF.exe, so will skip attempting to check '$Path' out of TFS source control." 813 | return 814 | } 815 | 816 | # Construct the checkout command to run. 817 | $tfCheckoutCommand = "& ""$tfPath"" checkout /lock:none ""$Path""" 818 | if ($Recursive) { $tfCheckoutCommand += " /recursive" } 819 | 820 | # Check the file out of TFS, eating any output and errors. 821 | Write-Verbose "About to run command '$tfCheckoutCommand'." 822 | Invoke-Expression -Command $tfCheckoutCommand 2>&1 > $null 823 | } 824 | 825 | function Tfs-IsItemCheckedOut 826 | { 827 | [CmdletBinding()] 828 | param 829 | ( 830 | [Parameter(Mandatory=$true, Position=0, HelpMessage="The local path to the file or folder to checkout from TFS source control.")] 831 | [string]$Path, 832 | 833 | [switch]$Recursive 834 | ) 835 | 836 | $tfPath = Get-TfExecutablePath 837 | 838 | # If we couldn't find TF.exe, just return without doing anything. 839 | if (Test-StringIsNullOrWhitespace $tfPath) 840 | { 841 | Write-Warning "Unable to locate TF.exe, so will skip attempting to check if '$Path' is checked out of TFS source control." 842 | return $null 843 | } 844 | 845 | # Construct the status command to run. 846 | $tfStatusCommand = "& ""$tfPath"" status ""$Path""" 847 | if ($Recursive) { $tfStatusCommand += " /recursive" } 848 | 849 | # Check the file out of TFS, capturing the output and errors. 850 | Write-Verbose "About to run command '$tfStatusCommand'." 851 | $status = (Invoke-Expression -Command $tfStatusCommand 2>&1) 852 | 853 | # Get the escaped path of the file or directory to search the status output for. 854 | $escapedPath = $Path.Replace('\', '\\') 855 | 856 | # Examine the returned text to return if the given Path is checked out or not. 857 | if ((Test-StringIsNullOrWhitespace $status) -or ($status -imatch $TF_EXE_NO_WORKING_FOLDER_MAPPING_ERROR_MESSAGE)) { return $null } # An error was returned, so likely TFS is not used for this item. 858 | elseif ($status -imatch $TF_EXE_NO_PENDING_CHANGES_MESSAGE) { return $false } # The item was found in TFS, but is not checked out. 859 | elseif ($status -imatch $escapedPath -and $status -imatch $TF_EXE_KEYWORD_IN_PENDING_CHANGES_MESSAGE) { return $true } # If the file path and "change(s)" are in the message then it means the path is checked out. 860 | else { return $false } # Else we're not sure, so return that it is not checked out. 861 | } 862 | 863 | function Tfs-Undo 864 | { 865 | [CmdletBinding()] 866 | param 867 | ( 868 | [Parameter(Mandatory=$true, Position=0, HelpMessage="The local path to the file or folder to undo from TFS source control.")] 869 | [string]$Path, 870 | 871 | [switch]$Recursive 872 | ) 873 | 874 | $tfPath = Get-TfExecutablePath 875 | 876 | # If we couldn't find TF.exe, just return without doing anything. 877 | if (Test-StringIsNullOrWhitespace $tfPath) 878 | { 879 | Write-Warning "Unable to locate TF.exe, so will skip attempting to undo '$Path' from TFS source control." 880 | return 881 | } 882 | 883 | # Construct the undo command to run. 884 | $tfCheckoutCommand = "& ""$tfPath"" undo ""$Path"" /noprompt" 885 | if ($Recursive) { $tfCheckoutCommand += " /recursive" } 886 | 887 | # Check the file out of TFS, eating any output and errors. 888 | Write-Verbose "About to run command '$tfCheckoutCommand'." 889 | Invoke-Expression -Command $tfCheckoutCommand 2>&1 > $null 890 | } 891 | 892 | function Get-ProjectsAssociatedNuSpecFilePath([parameter(Position=1,Mandatory=$true)][ValidateScript({Test-Path $_ -PathType Leaf})][string]$ProjectFilePath) 893 | { 894 | # Construct what the project's nuspec file path would be if it has one (i.e. a [Project File Name].nupsec file in the same directory as the project file). 895 | $projectsNuSpecFilePath = Join-Path ([System.IO.Path]::GetDirectoryName($ProjectFilePath)) ([System.IO.Path]::GetFileNameWithoutExtension($ProjectFilePath)) 896 | $projectsNuSpecFilePath += ".nuspec" 897 | 898 | # If this Project has a .nuspec that will be used to package with. 899 | if (Test-Path $projectsNuSpecFilePath -PathType Leaf) 900 | { 901 | return $projectsNuSpecFilePath 902 | } 903 | return $null 904 | } 905 | 906 | function Get-NuSpecsAssociatedProjectFilePath([parameter(Position=1,Mandatory=$true)][ValidateScript({Test-Path $_ -PathType Leaf})][string]$NuSpecFilePath) 907 | { 908 | # Construct what the nuspec's associated project file path would be if it has one (i.e. a [NuSpec File Name].[project extension] file in the same directory as the .nuspec file). 909 | $nuSpecsProjectFilePath = Join-Path ([System.IO.Path]::GetDirectoryName($NuSpecFilePath)) ([System.IO.Path]::GetFileNameWithoutExtension($NuSpecFilePath)) 910 | 911 | # Loop through each possible project extension type to see if it exists in the 912 | foreach ($extension in $VALID_NUGET_PROJECT_TYPE_EXTENSIONS_ARRAY) 913 | { 914 | # If this .nuspec file has an associated Project that can be used to pack with, return the project's file path. 915 | $nuSpecsProjectFilePath += $extension 916 | if (Test-Path $nuSpecsProjectFilePath -PathType Leaf) 917 | { 918 | return $nuSpecsProjectFilePath 919 | } 920 | } 921 | return $null 922 | } 923 | 924 | 925 | #========================================================== 926 | # Perform the script tasks. 927 | #========================================================== 928 | 929 | # Define some variables that we need to access within both the Try and Finally blocks of the script. 930 | $script:nuSpecFileWasAlreadyCheckedOut = $false 931 | $script:nuSpecFileContentsBeforeCheckout = $null 932 | $script:nuSpecLastWriteTimeBeforeCheckout = $null 933 | 934 | # Display the time that this script started running. 935 | $scriptStartTime = Get-Date 936 | Write-Verbose "New-NuGetPackage script started running at $($scriptStartTime.TimeOfDay.ToString())." 937 | 938 | # Display the version of PowerShell being used to run the script, as this can help solve some problems that are hard to reproduce on other machines. 939 | Write-Verbose "Using PowerShell Version: $($PSVersionTable.PSVersion.ToString())." 940 | 941 | try 942 | { 943 | # If we should not show any prompts, disable them all. 944 | if ($NoPrompt -or $NoPromptExceptOnError) 945 | { 946 | if ($NoPrompt) { $NoPromptForInputOnError = $true } 947 | $NoPromptForPushPackageToNuGetGallery = $true 948 | $NoPromptForReleaseNotes = $true 949 | $NoPromptForVersionNumber = $true 950 | } 951 | 952 | # If a path to a NuSpec, Project, or Package file to use was not provided, look for one in the same directory as this script or prompt for one. 953 | if ((Test-StringIsNullOrWhitespace $NuSpecFilePath) -and (Test-StringIsNullOrWhitespace $ProjectFilePath) -and (Test-StringIsNullOrWhitespace $PackageFilePath)) 954 | { 955 | # Get all of the .nuspec files in the script's directory. 956 | $nuSpecFiles = Get-ChildItem "$THIS_SCRIPTS_DIRECTORY_PATH\*" -Include "*.nuspec" -Name 957 | 958 | # Get all of the project files in the script's directory. 959 | $projectFiles = Get-ChildItem "$THIS_SCRIPTS_DIRECTORY_PATH\*" -Include $VALID_NUGET_PROJECT_TYPE_EXTENSIONS_WITH_WILDCARD_ARRAY -Name 960 | 961 | # Get all of the NuGet package files in this script's directory. 962 | $packageFiles = Get-ChildItem "$THIS_SCRIPTS_DIRECTORY_PATH\*" -Include "*.nupkg" -Name 963 | 964 | # Get the number of files found. 965 | $numberOfNuSpecFilesFound = @($nuSpecFiles).Length 966 | $numberOfProjectFilesFound = @($projectFiles).Length 967 | $numberOfPackageFilesFound = @($packageFiles).Length 968 | 969 | # If we only found one project file and no package files, see if we should use the project file. 970 | if (($numberOfProjectFilesFound -eq 1) -and ($numberOfPackageFilesFound -eq 0)) 971 | { 972 | $projectPath = Join-Path $THIS_SCRIPTS_DIRECTORY_PATH ($projectFiles | Select-Object -First 1) 973 | $projectsNuSpecFilePath = Get-ProjectsAssociatedNuSpecFilePath -ProjectFilePath $projectPath 974 | 975 | # If we didn't find any .nuspec files, then use this project file. 976 | if ($numberOfNuSpecFilesFound -eq 0) 977 | { 978 | $ProjectFilePath = $projectPath 979 | } 980 | # Else if we found one .nuspec file, see if we should use this project file. 981 | elseif ($numberOfNuSpecFilesFound -eq 1) 982 | { 983 | # If the .nuspec file belongs to this project file, use this project file. 984 | $nuSpecFilePathInThisScriptsDirectory = Join-Path $THIS_SCRIPTS_DIRECTORY_PATH ($nuSpecFiles | Select-Object -First 1) 985 | if ((!(Test-StringIsNullOrWhitespace $projectsNuSpecFilePath)) -and ($projectsNuSpecFilePath -eq $nuSpecFilePathInThisScriptsDirectory)) 986 | { 987 | $ProjectFilePath = $projectPath 988 | } 989 | } 990 | } 991 | # Else if we only found one .nuspec file and no project or package files, use the .nuspec file. 992 | elseif (($numberOfNuSpecFilesFound -eq 1) -and ($numberOfProjectFilesFound -eq 0) -and ($numberOfPackageFilesFound -eq 0)) 993 | { 994 | $NuSpecFilePath = Join-Path $THIS_SCRIPTS_DIRECTORY_PATH ($nuSpecFiles | Select-Object -First 1) 995 | } 996 | # Else if we only found one package file and no .nuspec or project files, use the package file. 997 | elseif (($numberOfPackageFilesFound -eq 1) -and ($numberOfNuSpecFilesFound -eq 0) -and ($numberOfProjectFilesFound -eq 0)) 998 | { 999 | $PackageFilePath = Join-Path $THIS_SCRIPTS_DIRECTORY_PATH ($packageFiles | Select-Object -First 1) 1000 | } 1001 | 1002 | # If we didn't find a clear .nuspec, project, or package file to use, prompt for one. 1003 | if ((Test-StringIsNullOrWhitespace $NuSpecFilePath) -and (Test-StringIsNullOrWhitespace $ProjectFilePath) -and (Test-StringIsNullOrWhitespace $PackageFilePath)) 1004 | { 1005 | # If we should prompt directly from PowerShell. 1006 | if ($UsePowerShellPrompts) 1007 | { 1008 | # Construct the prompt message with all of the supported project extensions. 1009 | # $promptmessage should end up looking like: "Enter the path to the .nuspec or project file (.csproj, .vbproj, .fsproj) to pack, or the package file (.nupkg) to push" 1010 | $promptMessage = "Enter the path to the .nuspec or project file (" 1011 | foreach ($extension in $VALID_NUGET_PROJECT_TYPE_EXTENSIONS_ARRAY) 1012 | { 1013 | $promptMessage += "$extension, " 1014 | } 1015 | $promptMessage = $promptMessage.Substring(0, $promptMessage.Length - 2) # Trim off the last character, as it will be a ", ". 1016 | $promptMessage += ") to pack, or .nupkg file to push" 1017 | 1018 | $filePathToUse = Read-Host $promptMessage 1019 | $filePathToUse = $filePathToUse.Trim('"') 1020 | } 1021 | # Else use a nice GUI prompt. 1022 | else 1023 | { 1024 | # Construct the strings to use in the OpenFileDialog filter to allow all of the supported project file types. 1025 | # $filter should end up looking like: "NuSpec, package, and project files (*.nuspec, *.nupkg, *.csproj, *.vbproj, *.fsproj)|*.nuspec;*.nupkg;*.csproj;*.vbproj;*.fsproj" 1026 | $filterMessage = "NuSpec and project files (*.nuspec, " 1027 | $filterTypes = "*.nuspec;*.nupkg;" 1028 | foreach ($extension in $VALID_NUGET_PROJECT_TYPE_EXTENSIONS_ARRAY) 1029 | { 1030 | $filterMessage += "*$extension, " 1031 | $filterTypes += "*$extension;" 1032 | } 1033 | $filterMessage = $filterMessage.Substring(0, $filterMessage.Length - 2) # Trim off the last 2 characters, as they will be a ", ". 1034 | $filterMessage += ")" 1035 | $filterTypes = $filterTypes.Substring(0, $filterTypes.Length - 1) # Trim off the last character, as it will be a ";". 1036 | $filter = "$filterMessage|$filterTypes" 1037 | 1038 | $filePathToUse = Read-OpenFileDialog -WindowTitle "Select the .nuspec or project file to pack, or the package file (.nupkg) to push..." -InitialDirectory $THIS_SCRIPTS_DIRECTORY_PATH -Filter $filter 1039 | } 1040 | 1041 | # If the user cancelled the file dialog, throw an error since we don't have a .nuspec file to use. 1042 | if (Test-StringIsNullOrWhitespace $filePathToUse) 1043 | { 1044 | throw "No .nuspec, project, or package file was specified. You must specify a valid file to use." 1045 | } 1046 | 1047 | # If a .nuspec file was specified, double check that we should use it. 1048 | if ([System.IO.Path]::GetExtension($filePathToUse) -eq ".nuspec") 1049 | { 1050 | # If this .nuspec file is associated with a project file, prompt to see if they want to pack the project instead (as that is preferred). 1051 | $projectPath = Get-NuSpecsAssociatedProjectFilePath -NuSpecFilePath $filePathToUse 1052 | if (!(Test-StringIsNullOrWhitespace $projectPath)) 1053 | { 1054 | # If we are not allowed to prompt the user, just assume we should only use the .nuspec file. 1055 | if ($NoPrompt) 1056 | { 1057 | $answer = "No" 1058 | } 1059 | # Else prompt the user if they want to pack the project file instead. 1060 | else 1061 | { 1062 | $promptMessage = "The selected .nuspec file appears to be associated with the project file:`n`n$projectPath`n`nIt is generally preferred to pack the project file, and the .nuspec file will automatically get picked up.`nDo you want to pack the project file instead?" 1063 | 1064 | # If we should prompt directly from PowerShell. 1065 | if ($UsePowerShellPrompts) 1066 | { 1067 | $promptMessage += " (Yes|No|Cancel)" 1068 | $answer = Read-Host $promptMessage 1069 | } 1070 | # Else use a nice GUI prompt. 1071 | else 1072 | { 1073 | $answer = Read-MessageBoxDialog -Message $promptMessage -WindowTitle "Pack using the Project file instead?" -Buttons YesNoCancel -Icon Question 1074 | } 1075 | } 1076 | 1077 | # If the user wants to use the Project file, use it. 1078 | if (($answer -is [string] -and $answer.StartsWith("Y", [System.StringComparison]::InvariantCultureIgnoreCase)) -or $answer -eq [System.Windows.Forms.DialogResult]::Yes) 1079 | { 1080 | $ProjectFilePath = $projectPath 1081 | } 1082 | # Else if the user wants to use the .nuspec file, use it. 1083 | elseif (($answer -is [string] -and $answer.StartsWith("N", [System.StringComparison]::InvariantCultureIgnoreCase)) -or $answer -eq [System.Windows.Forms.DialogResult]::No) 1084 | { 1085 | $NuSpecFilePath = $filePathToUse 1086 | } 1087 | # Else the user cancelled the prompt, so exit the script. 1088 | else 1089 | { 1090 | throw "User cancelled the .nuspec or project file prompt, so exiting script." 1091 | } 1092 | } 1093 | # Else this .nuspec file is not associated with a project file, so use the .nuspec file. 1094 | else 1095 | { 1096 | $NuSpecFilePath = $filePathToUse 1097 | } 1098 | } 1099 | # Else if a package file was specified. 1100 | elseif ([System.IO.Path]::GetExtension($filePathToUse) -eq ".nupkg") 1101 | { 1102 | $PackageFilePath = $filePathToUse 1103 | } 1104 | # Else a .nuspec or package file was not specified, so assume it is a project file. 1105 | else 1106 | { 1107 | $ProjectFilePath = $filePathToUse 1108 | } 1109 | } 1110 | } 1111 | 1112 | # Make sure we have the absolute file paths. 1113 | if (!(Test-StringIsNullOrWhitespace $NuSpecFilePath)) { $NuSpecFilePath = Resolve-Path $NuSpecFilePath } 1114 | if (!(Test-StringIsNullOrWhitespace $ProjectFilePath)) { $ProjectFilePath = Resolve-Path $ProjectFilePath } 1115 | if (!(Test-StringIsNullOrWhitespace $PackageFilePath)) { $PackageFilePath = Resolve-Path $PackageFilePath } 1116 | 1117 | # If a path to the NuGet executable was not provided, try and find it. 1118 | if (Test-StringIsNullOrWhitespace $NuGetExecutableFilePath) 1119 | { 1120 | # If the NuGet executable is in the same directory as this script, use it. 1121 | $nuGetExecutablePathInThisDirectory = Join-Path $THIS_SCRIPTS_DIRECTORY_PATH "NuGet.exe" 1122 | if (Test-Path $nuGetExecutablePathInThisDirectory) 1123 | { 1124 | $NuGetExecutableFilePath = $nuGetExecutablePathInThisDirectory 1125 | } 1126 | # Else we don't know where the executable is, so assume it has been added to the PATH. 1127 | else 1128 | { 1129 | $NuGetExecutableFilePath = "NuGet.exe" 1130 | } 1131 | } 1132 | 1133 | # If we should try and update the NuGet executable. 1134 | if ($UpdateNuGetExecutable) 1135 | { 1136 | # If we have the path to the NuGet executable, try and check it out of TFS before having it update itself. 1137 | if (Test-Path $NuGetExecutableFilePath) 1138 | { 1139 | # Try and check the NuGet executable out of TFS if needed. 1140 | $nuGetExecutableWasAlreadyCheckedOut = Tfs-IsItemCheckedOut -Path $NuGetExecutableFilePath 1141 | if ($nuGetExecutableWasAlreadyCheckedOut -eq $false) { Tfs-Checkout -Path $NuGetExecutableFilePath } 1142 | } 1143 | 1144 | # Create the command to use to update NuGet.exe. 1145 | $updateCommand = "& ""$NuGetExecutableFilePath"" update -self" 1146 | 1147 | # Have the NuGet executable try and auto-update itself. 1148 | Write-Verbose "About to run Update command '$updateCommand'." 1149 | $updateOutput = (Invoke-Expression -Command $updateCommand | Out-String).Trim() 1150 | 1151 | # Write the output of the above command to the Verbose stream. 1152 | Write-Verbose $updateOutput 1153 | 1154 | # If we have the path to the NuGet executable, we checked it out of TFS, and it did not auto-update itself, then undo the changes from TFS. 1155 | if ((Test-Path $NuGetExecutableFilePath) -and ($nuGetExecutableWasAlreadyCheckedOut -eq $false) -and !$updateOutput.EndsWith($NUGET_EXE_SUCCESSFULLY_UPDATED_TO_NEW_VERSION.Trim())) 1156 | { 1157 | Tfs-Undo -Path $NuGetExecutableFilePath 1158 | } 1159 | } 1160 | 1161 | # Get and display the version of NuGet.exe that will be used. If NuGet.exe is not found an exception will be thrown automatically. 1162 | # Create the command to use to get the Nuget Help info. 1163 | $helpCommand = "& ""$NuGetExecutableFilePath""" 1164 | 1165 | # Get the NuGet.exe Help output. 1166 | Write-Verbose "About to run Help command '$helpCommand'." 1167 | $helpOutput = (Invoke-Expression -Command $helpCommand | Out-String).Trim() 1168 | 1169 | # If no Help output was retrieved, the NuGet.exe likely returned an error. 1170 | if (Test-StringIsNullOrWhitespace $helpOutput) 1171 | { 1172 | # Get the error information returned by NuGet.exe, and throw an error that we could not run NuGet.exe as expected. 1173 | $helpError = (Invoke-Expression -Command $helpCommand 2>&1 | Out-String).Trim() 1174 | throw "NuGet information could not be retrieved by running '$NuGetExecutableFilePath'.`r`n`r`nRunning '$NuGetExecutableFilePath' returns the following information:`r`n`r`n$helpError" 1175 | } 1176 | 1177 | # Display the version of the NuGet.exe. This information is the first line of the NuGet Help output. 1178 | $nuGetVersionLine = ($helpOutput -split "`r`n")[0] 1179 | Write-Verbose "Using $($nuGetVersionLine)." 1180 | 1181 | # Force NuGet.exe to output English so that we can properly parse and match against it's output. 1182 | # The -ForceEnglishOutput switch was only added in NuGet.exe v3.5, so default to using it, and remove it if the version is less than v3.5. 1183 | $nuGetForceEnglishOutputSwitch = " -ForceEnglishOutput" 1184 | $PackOptions += $nuGetForceEnglishOutputSwitch 1185 | [array]$nuGetVersionParts = $null 1186 | $nugetVersionMatch = $NUGET_EXE_VERSION_NUMBER_REGEX.Match($nuGetVersionLine) 1187 | if ($nugetVersionMatch.Success) 1188 | { 1189 | # Get the version of NuGet.exe being used. 1190 | $nuGetVersionString = $nugetVersionMatch.Groups["Version"].Value 1191 | 1192 | if (!(Test-StringIsNullOrWhitespace $nuGetVersionString)) 1193 | { 1194 | # If we are using a version of NuGet.exe less than v3.5, remove the switch to force English output. 1195 | $nuGetVersionParts = $nuGetVersionString -split "\." 1196 | if ($nuGetVersionParts.Count -ge 2) 1197 | { 1198 | if ($nuGetVersionParts[0] -le 2 -or ($nuGetVersionParts[0] -eq 3 -and $nuGetVersionParts[1] -lt 5)) 1199 | { 1200 | $PackOptions = $PackOptions.Replace($nuGetForceEnglishOutputSwitch, [string]::Empty) 1201 | } 1202 | } 1203 | } 1204 | } 1205 | 1206 | # If we weren't actually able to determine which version of NuGet.exe is being used, display a warning. 1207 | if ($nuGetVersionParts -eq $null -or $nuGetVersionParts.Count -lt 2) 1208 | { 1209 | Write-Warning "Could not determine which version of NuGet.exe is being used." 1210 | } 1211 | 1212 | # Declare the backup directory to create the NuGet Package in, as not all code paths will set it (i.e. when pushing an existing package), but we check it later. 1213 | $defaultDirectoryPathToPutNuGetPackageIn = $null 1214 | 1215 | # If we were not given a package file, then we need to pack something. 1216 | if (Test-StringIsNullOrWhitespace $PackageFilePath) 1217 | { 1218 | # If we were given a Project to package. 1219 | if (!(Test-StringIsNullOrWhitespace $ProjectFilePath)) 1220 | { 1221 | # Get the project's .nuspec file path, if it has a .nuspec file. 1222 | $projectNuSpecFilePath = Get-ProjectsAssociatedNuSpecFilePath -ProjectFilePath $ProjectFilePath 1223 | 1224 | # If this Project has a .nuspec that will be used to package with. 1225 | if (!(Test-StringIsNullOrWhitespace $projectNuSpecFilePath)) 1226 | { 1227 | # Update .nuspec file based on user input. 1228 | $NuSpecFilePath = $projectNuSpecFilePath 1229 | Update-NuSpecFile 1230 | } 1231 | # Else we aren't using a .nuspec file, so if a Version Number was given in the script parameters but not the pack parameters, add it to the pack parameters. 1232 | elseif (!(Test-StringIsNullOrWhitespace $VersionNumber) -and $PackOptions -notmatch '-Version') 1233 | { 1234 | $PackOptions += " -Version ""$VersionNumber""" 1235 | } 1236 | 1237 | # Save the directory that the project file is in as the directory to create the package in. 1238 | $defaultDirectoryPathToPutNuGetPackageIn = [System.IO.Path]::GetDirectoryName($ProjectFilePath) 1239 | 1240 | # Record that we want to pack using the project file, not a NuSpec file. 1241 | $fileToPack = $ProjectFilePath 1242 | } 1243 | # Else we are supposed to package using just a NuSpec. 1244 | else 1245 | { 1246 | # Update .nuspec file based on user input. 1247 | Update-NuSpecFile 1248 | 1249 | # Save the directory that the .nuspec file is in as the directory to create the package in. 1250 | $defaultDirectoryPathToPutNuGetPackageIn = [System.IO.Path]::GetDirectoryName($NuSpecFilePath) 1251 | 1252 | # Record that we want to pack using the NuSpec file, not a project file. 1253 | $fileToPack = $NuSpecFilePath 1254 | } 1255 | 1256 | # Make sure our backup Output Directory is an absolute path. 1257 | if (![System.IO.Path]::IsPathRooted($defaultDirectoryPathToPutNuGetPackageIn)) 1258 | { 1259 | $defaultDirectoryPathToPutNuGetPackageIn = Resolve-Path $directoryToPackFrom 1260 | } 1261 | 1262 | # When an Output Directory is not explicitly provided, we want to put generated packages into their own directory. 1263 | $defaultDirectoryPathToPutNuGetPackageIn = Join-Path $defaultDirectoryPathToPutNuGetPackageIn $DEFAULT_DIRECTORY_TO_PUT_NUGET_PACKAGES_IN 1264 | 1265 | # If the user did not specify an Output Directory. 1266 | if ($PackOptions -notmatch '-OutputDirectory') 1267 | { 1268 | # Insert our default Output Directory into the Additional Pack Options. 1269 | Write-Verbose "Specifying to use the default Output Directory '$defaultDirectoryPathToPutNuGetPackageIn'." 1270 | $PackOptions += " -OutputDirectory ""$defaultDirectoryPathToPutNuGetPackageIn""" 1271 | 1272 | # Make sure the Output Directory we are adding exists. 1273 | if (!(Test-Path -Path $defaultDirectoryPathToPutNuGetPackageIn)) 1274 | { 1275 | New-Item -Path $defaultDirectoryPathToPutNuGetPackageIn -ItemType Directory > $null 1276 | } 1277 | } 1278 | 1279 | # Create the command to use to create the package. 1280 | $packCommand = "& ""$NuGetExecutableFilePath"" pack ""$fileToPack"" $PackOptions" 1281 | $packCommand = $packCommand -ireplace ';', '`;' # Escape any semicolons so they are not interpreted as the start of a new command. 1282 | 1283 | # Create the package. 1284 | Write-Verbose "About to run Pack command '$packCommand'." 1285 | $packOutput = (Invoke-Expression -Command $packCommand | Out-String).Trim() 1286 | 1287 | # Write the output of the above command to the Verbose stream. 1288 | Write-Verbose $packOutput 1289 | 1290 | # Get the path the NuGet Package was created to, and write it to the output stream. 1291 | $match = $NUGET_EXE_SUCCESSFULLY_CREATED_PACKAGE_MESSAGE_REGEX.Match($packOutput) 1292 | if ($match.Success) 1293 | { 1294 | $nuGetPackageFilePath = $match.Groups["FilePath"].Value 1295 | 1296 | # Have this cmdlet return the path that the new NuGet Package was created to. 1297 | # This should be the only code that uses Write-Output, as it is the only thing that should be returned by the cmdlet. 1298 | Write-Output $nuGetPackageFilePath 1299 | } 1300 | else 1301 | { 1302 | throw "Could not determine where NuGet Package was created to. This typically means that an error occurred while NuGet.exe was packing it. Look for errors from NuGet.exe above (in the console window), or in the following NuGet.exe output. You can also try running this command with the -Verbose switch for more information:{0}{1}" -f [Environment]::NewLine, $packOutput 1303 | } 1304 | } 1305 | # Else we were given a Package file to push. 1306 | else 1307 | { 1308 | # Save the Package file path to push. 1309 | $nuGetPackageFilePath = $PackageFilePath 1310 | } 1311 | 1312 | # Get the Source to push the package to. 1313 | # If the user explicitly provided the Source to push the package to, get it. 1314 | $rxSourceToPushPackageTo = [regex] "(?i)((-Source|-src)\s+(?.*?)(\s+|$))" 1315 | $match = $rxSourceToPushPackageTo.Match($PushOptions) 1316 | if ($match.Success) 1317 | { 1318 | $sourceToPushPackageTo = $match.Groups["Source"].Value 1319 | 1320 | # Strip off any single or double quotes around the address. 1321 | $sourceToPushPackageTo = $sourceToPushPackageTo.Trim([char[]]@("'", '"')) 1322 | } 1323 | # Else they did not provide an explicit source to push to, so set it to the default. 1324 | else 1325 | { 1326 | # Assume they are pushing to the typical default source. 1327 | $sourceToPushPackageTo = $DEFAULT_NUGET_SOURCE_TO_PUSH_TO 1328 | 1329 | # Update the PushOptions to include the default source (as -Source is now a required parameter as of NuGet.exe v3.4.2). 1330 | $PushOptions = $PushOptions.Trim() + " -Source $sourceToPushPackageTo" 1331 | } 1332 | 1333 | # If the switch to push the package to the gallery was not provided and we are allowed to prompt, prompt the user if they want to push the package. 1334 | if (!$PushPackageToNuGetGallery -and !$NoPromptForPushPackageToNuGetGallery) 1335 | { 1336 | $promptMessage = "Do you want to push this package:`n'$nuGetPackageFilePath'`nto the NuGet Gallery '$sourceToPushPackageTo'?" 1337 | 1338 | # If we should prompt directly from PowerShell. 1339 | if ($UsePowerShellPrompts) 1340 | { 1341 | $promptMessage += " (Yes|No)" 1342 | $answer = Read-Host $promptMessage 1343 | } 1344 | # Else use a nice GUI prompt. 1345 | else 1346 | { 1347 | $answer = Read-MessageBoxDialog -Message $promptMessage -WindowTitle "Push Package To Gallery?" -Buttons YesNo -Icon Question 1348 | } 1349 | 1350 | # If the user wants to push the new package, record it. 1351 | if (($answer -is [string] -and $answer.StartsWith("Y", [System.StringComparison]::InvariantCultureIgnoreCase)) -or $answer -eq [System.Windows.Forms.DialogResult]::Yes) 1352 | { 1353 | $PushPackageToNuGetGallery = $true 1354 | } 1355 | } 1356 | 1357 | # If we should push the Nuget package to the gallery. 1358 | if ($PushPackageToNuGetGallery) 1359 | { 1360 | # If the user has not provided an API key. 1361 | $UserProvidedApiKeyUsingPrompt = $false 1362 | if ($PushOptions -notmatch '-ApiKey') 1363 | { 1364 | # Get the NuGet.config file contents as Xml. 1365 | $nuGetConfigXml = New-Object System.Xml.XmlDocument 1366 | $nuGetConfigXml.Load($NUGET_CONFIG_FILE_PATH) 1367 | 1368 | # If the user does not have an API key saved on this PC for the Source to push to, and prompts are allowed, prompt them for one. 1369 | if (((Get-XmlNodes -XmlDocument $nuGetConfigXml -NodePath "configuration.apikeys.add" | Where-Object { $_.key -eq $sourceToPushPackageTo }) -eq $null) -and !$NoPrompt) 1370 | { 1371 | $promptMessage = "It appears that you do not have an API key saved on this PC for the source to push the package to '$sourceToPushPackageTo'.`n`nYou must provide an API key to push this package to the NuGet Gallery.`n`nPlease enter your API key" 1372 | 1373 | # If we should prompt directly from PowerShell. 1374 | if ($UsePowerShellPrompts) 1375 | { 1376 | $apiKey = Read-Host $promptMessage 1377 | } 1378 | # Else use a nice GUI prompt. 1379 | else 1380 | { 1381 | $apiKey = Read-InputBoxDialog -Message "$promptMessage`:" -WindowTitle "Enter Your API Key" 1382 | } 1383 | 1384 | # If the user supplied an Api Key. 1385 | if (!(Test-StringIsNullOrWhitespace $apiKey)) 1386 | { 1387 | # Add the given Api Key to the Push Options. 1388 | $PushOptions += " -ApiKey $apiKey" 1389 | 1390 | # Record that the user provided the Api Key via a prompt. 1391 | $UserProvidedApiKeyUsingPrompt = $true 1392 | } 1393 | } 1394 | } 1395 | 1396 | # Create the command to use to push the package to the gallery. 1397 | $pushCommand = "& ""$NuGetExecutableFilePath"" push ""$nuGetPackageFilePath"" $PushOptions" 1398 | $pushCommand = $pushCommand -ireplace ';', '`;' # Escape any semicolons so they are not interpreted as the start of a new command. 1399 | 1400 | # Push the package to the gallery. 1401 | Write-Verbose "About to run Push command '$pushCommand'." 1402 | $pushOutput = (Invoke-Expression -Command $pushCommand | Out-String).Trim() 1403 | 1404 | # Write the output of the above command to the Verbose stream. 1405 | Write-Verbose $pushOutput 1406 | 1407 | # If an error occurred while pushing the package, throw and error. Else it was pushed successfully. 1408 | if (!$pushOutput.EndsWith($NUGET_EXE_SUCCESSFULLY_PUSHED_PACKAGE_MESSAGE.Trim())) 1409 | { 1410 | throw "Could not determine if package was pushed to gallery successfully. Perhaps an error occurred while pushing it. Look for errors from NuGet.exe above (in the console window), or in the following NuGet.exe output. You can also try running this command with the -Verbose switch for more information:{0}{1}" -f [Environment]::NewLine, $pushOutput 1411 | } 1412 | 1413 | # If the package should be deleted. 1414 | if ($DeletePackageAfterPush -and (Test-Path $nuGetPackageFilePath)) 1415 | { 1416 | # Delete the package. 1417 | Write-Verbose "Deleting NuGet Package '$nuGetPackageFilePath'." 1418 | Remove-Item -Path $nuGetPackageFilePath -Force 1419 | 1420 | # If the package was output to the default directory, and the directory is now empty, delete the default directory too since we would have created it above. 1421 | if (!(Test-StringIsNullOrWhitespace $defaultDirectoryPathToPutNuGetPackageIn) -and (Test-Path -Path $defaultDirectoryPathToPutNuGetPackageIn)) 1422 | { 1423 | [int]$numberOfFilesInDefaultOutputDirectory = ((Get-ChildItem -Path $defaultDirectoryPathToPutNuGetPackageIn -Force) | Measure-Object).Count 1424 | if ((Split-Path -Path $nuGetPackageFilePath -Parent) -eq $defaultDirectoryPathToPutNuGetPackageIn -and $numberOfFilesInDefaultOutputDirectory -eq 0) 1425 | { 1426 | Write-Verbose "Deleting empty default NuGet package directory '$defaultDirectoryPathToPutNuGetPackageIn'." 1427 | Remove-Item -Path $defaultDirectoryPathToPutNuGetPackageIn -Force 1428 | } 1429 | } 1430 | } 1431 | 1432 | # If the user provided the Api Key via a prompt from this script, prompt them for if they want to save the given API key on this PC. 1433 | if ($UserProvidedApiKeyUsingPrompt) 1434 | { 1435 | # If we are not allowed to prompt the user, just assume they don't want to save the key on this PC. 1436 | if ($NoPrompt) 1437 | { 1438 | $answer = "No" 1439 | } 1440 | # Else prompt the user if they want to save the given API key on this PC. 1441 | else 1442 | { 1443 | $promptMessage = "Do you want to save the API key you provided on this PC so that you don't have to enter it again next time?" 1444 | 1445 | # If we should prompt directly from PowerShell. 1446 | if ($UsePowerShellPrompts) 1447 | { 1448 | $promptMessage += " (Yes|No)" 1449 | $answer = Read-Host $promptMessage 1450 | } 1451 | # Else use a nice GUI prompt. 1452 | else 1453 | { 1454 | $answer = Read-MessageBoxDialog -Message $promptMessage -WindowTitle "Save API Key On This PC?" -Buttons YesNo -Icon Question 1455 | } 1456 | } 1457 | 1458 | # If the user wants to save the API key. 1459 | if (($answer -is [string] -and $answer.StartsWith("Y", [System.StringComparison]::InvariantCultureIgnoreCase)) -or $answer -eq [System.Windows.Forms.DialogResult]::Yes) 1460 | { 1461 | # Create the command to use to save the Api key on this PC. 1462 | $setApiKeyCommand = "& ""$NuGetExecutableFilePath"" setApiKey ""$apiKey"" -Source ""$sourceToPushPackageTo""" 1463 | $setApiKeyCommand = $setApiKeyCommand -ireplace ';', '`;' # Escape any semicolons so they are not interpreted as the start of a new command. 1464 | 1465 | # Save the Api key on this PC. 1466 | Write-Verbose "About to run command '$setApiKeyCommand'." 1467 | $setApiKeyOutput = (Invoke-Expression -Command $setApiKeyCommand | Out-String).Trim() 1468 | 1469 | # Write the output of the above command to the Verbose stream. 1470 | Write-Verbose $setApiKeyOutput 1471 | 1472 | # Determine if the API Key was saved successfully, and throw an error if it wasn't. 1473 | $expectedSuccessfulNuGetSetApiKeyOutput = ($NUGET_EXE_SUCCESSFULLY_SAVED_API_KEY_MESSAGE -f $apiKey, $sourceToPushPackageTo) # "The API Key '$apiKey' was saved for '$sourceToPushPackageTo'." 1474 | if ($setApiKeyOutput -ne $expectedSuccessfulNuGetSetApiKeyOutput.Trim()) 1475 | { 1476 | throw "Could not determine if the API key was saved successfully. Perhaps an error occurred while saving it. Look for errors from NuGet.exe above (in the console window), or in the following NuGet.exe output. You can also try running this command with the -Verbose switch for more information:{0}{1}" -f [Environment]::NewLine, $packOutput 1477 | } 1478 | } 1479 | } 1480 | } 1481 | } 1482 | finally 1483 | { 1484 | Write-Verbose "Performing any required New-NuGetPackage script cleanup..." 1485 | 1486 | # If we have a NuSpec file path. 1487 | if (!(Test-StringIsNullOrWhitespace $NuSpecFilePath)) 1488 | { 1489 | # If we should revert any changes we made to the NuSpec file. 1490 | if ($DoNotUpdateNuSpecFile) 1491 | { 1492 | # If we created a backup of the NuSpec file before updating it, restore the backed up version. 1493 | $backupNuSpecFilePath = Get-NuSpecBackupFilePath 1494 | if (Test-Path $backupNuSpecFilePath -PathType Leaf) 1495 | { 1496 | Copy-Item -Path $backupNuSpecFilePath -Destination $NuSpecFilePath -Force 1497 | Remove-Item -Path $backupNuSpecFilePath -Force 1498 | } 1499 | } 1500 | 1501 | # If we checked the NuSpec file out from TFS. 1502 | if ((Test-Path $NuSpecFilePath) -and ($script:nuSpecFileWasAlreadyCheckedOut -eq $false)) 1503 | { 1504 | # If the NuSpec file should not be updated, or the contents have not been changed. 1505 | $newNuSpecFileContents = [System.IO.File]::ReadAllText($NuSpecFilePath) 1506 | if ($DoNotUpdateNuSpecFile -or ($script:nuSpecFileContentsBeforeCheckout -eq $newNuSpecFileContents)) 1507 | { 1508 | # Try and undo our checkout from TFS. 1509 | Tfs-Undo -Path $NuSpecFilePath 1510 | 1511 | # Also reset the file's LastWriteTime so that MSBuild does not always rebuild the project because it thinks the .nuspec file was modified after the project's .pdb file. 1512 | # If we recorded the NuSpec file's last write time, then reset it. 1513 | if ($script:nuSpecLastWriteTimeBeforeCheckout -ne $null) 1514 | { 1515 | # We first have to make sure the file is writable before trying to set the LastWriteTime, and then restore the Read-Only attribute if it was set before. 1516 | $nuspecFileInfo = New-Object System.IO.FileInfo($NuSpecFilePath) 1517 | $nuspecFileIsReadOnly = $nuspecFileInfo.IsReadOnly 1518 | $nuspecFileInfo.IsReadOnly = $false 1519 | [System.IO.File]::SetLastWriteTime($NuSpecFilePath, $script:nuSpecLastWriteTimeBeforeCheckout) 1520 | if ($nuspecFileIsReadOnly) { $nuspecFileInfo.IsReadOnly = $true } 1521 | } 1522 | } 1523 | } 1524 | } 1525 | } 1526 | 1527 | # Display the time that this script finished running, and how long it took to run. 1528 | $scriptFinishTime = Get-Date 1529 | $scriptElapsedTimeInSeconds = ($scriptFinishTime - $scriptStartTime).TotalSeconds.ToString() 1530 | Write-Verbose "New-NuGetPackage script finished running at $($scriptFinishTime.TimeOfDay.ToString()). Completed in $scriptElapsedTimeInSeconds seconds." 1531 | -------------------------------------------------------------------------------- /tools/PublishNewNuGetPackage/tools/Install.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deadlydog/AutoUpdateProjectsMinimumRequiredClickOnceVersion/f0b8b219584e690bb2593001f9593bd44e92e06e/tools/PublishNewNuGetPackage/tools/Install.ps1 -------------------------------------------------------------------------------- /tools/PublishNewNuGetPackage/tools/Uninstall.ps1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deadlydog/AutoUpdateProjectsMinimumRequiredClickOnceVersion/f0b8b219584e690bb2593001f9593bd44e92e06e/tools/PublishNewNuGetPackage/tools/Uninstall.ps1 --------------------------------------------------------------------------------