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?
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With