DEV Community

Sheldon
Sheldon

Posted on • Originally published at sheldonhull.com on

Bump nuspec file version with powershell

Bump Nuspec Version

Bumping the version of the nuspec file requires a little tweaking and I got some help from the slack powershell community to ensure I handled the xml parsing correctly. This was the result. If you are running a chocolatey package build or equivalent nuspec build via an agent and want a way to ensure the latest build updates the build version incrementally this should help.

This snippet should help give you a way to bump a nuspec file version programmatically.

#requires -Module PSFramework
<#
.Description
incrementally bump the version of a nuspec file, with support for what if and updated summary from readme
#>
[cmdletbinding(SupportsShouldProcess)]
param()
try
{
$Directory = $PSScriptRoot
if ($null -eq $Directory)
{
throw "Cannot run interactively. Call file from prompt, as it needs PSScriptRoot variable to package"
}
# Update Version in Nuspec
[string]$NuSpecFile = (Get-ChildItem -path $Directory -Filter *.nuspec | Select-Object -First 1).fullname
[xml]$xml = Get-Content -path $NuSpecFile -Raw
$ns = [System.Xml.XmlNamespaceManager]::new($xml.NameTable)
$ns.AddNamespace('nuspec', 'http://schemas.microsoft.com/packaging/2015/06/nuspec.xsd')
[version]$Version = [version]::parse($xml.SelectSingleNode('/nuspec:package/nuspec:metadata/nuspec:version', $ns).InnerText)
[version]$NewVersion = [version]::new($Version.Major, $Version.Minor, ($Version.Build + 1))
$xml.SelectSingleNode('/nuspec:package/nuspec:metadata/nuspec:version', $ns).InnerText = $NewVersion.ToString()
$xml.SelectSingleNode('/nuspec:package/nuspec:metadata/nuspec:description', $ns).InnerText = Get-Content -Raw (Join-Path $Directory 'ReadMe.md')
if ($PSCmdlet.ShouldProcess($NuSpecFile, "Version: $($Version.ToString()) bumped to $($NewVersion.ToString()) and file saved"))
{
$xml.Save($NuSpecFile)
Write-PSFMessage -Level Important -Message "$NuSpecFile -- Original Version: $Version -- Updated to $NewVersion"
}
}
catch
{
throw
}

I modified the logic to support -WhatIf since I'm a fan of being able to run stuff like this without actually breaking things first.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay