PowerShell - 从 .csproj 文件获取版本 [英] PowerShell - Get Version from .csproj file
问题描述
我正在学习 PowerShell.现在,我正在尝试从 .csproj 文件中获取 Version
元素值..csproj 文件的 XML 如下所示:
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>
为了从这个 XML 中获取 Version
元素值,我编写了以下 PowerShell 脚本:
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:
请注意,项目 XML 和版本均未写入.起初,我以为我错误地引用了 .csproj.我故意删除了最后的j",并抛出了一个错误.出于这个原因,我假设我正在正确加载 .csproj 内容.但是,我相信我没有在我的 PowerShell 脚本中正确解析 XML.
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.
如何从 PowerShell 脚本中的 .csproj 值中获取 Version
?
How do I get the Version
from the .csproj value in the PowerShell script?
推荐答案
如前所述,Write-Host
仅用于输出,无法重定向.除此之外,我无法重现它.这对我有用:
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
(转换为 [Version]
可以更轻松地获取版本的各个部分,与其他版本进行比较等)
(The cast to [Version]
makes it easier to get the individual parts of the version, compare with other versions, etc.)
这篇关于PowerShell - 从 .csproj 文件获取版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!