Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell - Get Version from .csproj file

Tags:

c#

powershell

I'm learning PowerShell. Right now, I'm trying to get the Version element value from a .csproj file. The .csproj file's XML looks like this:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <Version>1.2.3</Version>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="MyLibrary" Version="3.2.1" />
  </ItemGroup>

</Project>

In an attempt to get the Version element value from this XML, I've written the following PowerShell script:

$xml = [xml](Get-Content ./MyApp.csproj)

Write-Host "xml: " $xml

$version = $xml.Project.PropertyGroup.Version

Write-Host "version: $version"

When I run this script, I see the following:

xml:

version:

Notice that neither the project XML, nor the version gets written. At first, I thought I was referencing the .csproj incorrectly. I intentionally removed the "j" at the end and an error was thrown. For that reason, I'm assuming that I'm properly loading the .csproj content. However, I believe I'm not parsing the XML properly in my PowerShell script.

How do I get the Version from the .csproj value in the PowerShell script?

like image 322
Some User Avatar asked Sep 12 '18 14:09

Some User


1 Answers

As noted, Write-Host is output-only and cannot be redirected. Other than that, I can't reproduce it. This works for me:

$xml = [Xml] (Get-Content .\MyApp.csproj)
$version = [Version] $xml.Project.PropertyGroup.Version

(The cast to [Version] makes it easier to get the individual parts of the version, compare with other versions, etc.)

like image 186
Bill_Stewart Avatar answered Oct 21 '22 06:10

Bill_Stewart