简体   繁体   English

PowerShell-从.csproj文件获取版本

[英]PowerShell - Get Version from .csproj file

I'm learning PowerShell. 我正在学习PowerShell。 Right now, I'm trying to get the Version element value from a .csproj file. 现在,我正在尝试从.csproj文件中获取Version元素值。 The .csproj file's XML looks like this: .csproj文件的XML如下所示:

<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获取Version元素值,我编写了以下PowerShell脚本:

$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. 请注意,项目XML和版本均未写入。 At first, I thought I was referencing the .csproj incorrectly. 起初,我以为我是错误地引用了.csproj。 I intentionally removed the "j" at the end and an error was thrown. 我有意删除了最后的“ j”,并引发了错误。 For that reason, I'm assuming that I'm properly loading the .csproj content. 因此,我假设我正在正确加载.csproj内容。 However, I believe I'm not parsing the XML properly in my PowerShell script. 但是,我相信我无法在PowerShell脚本中正确解析XML。

How do I get the Version from the .csproj value in the PowerShell script? 如何从PowerShell脚本中的.csproj值获取Version

As noted, Write-Host is output-only and cannot be redirected. 如前所述, Write-Host是仅输出的,无法重定向。 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.) (通过强制转换为[Version] ,可以更轻松地获取版本的各个部分,与其他版本进行比较,等等。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM