用于更改 csproj 文件中的值的 Powershell 脚本

问题描述

我想更改以下 test.csproj 文件中 ProductVersion 标记的值。我只需要将 ProductVersion: 8A-0V-W3 第一次出现的值更改为 A0-B0-C0

int3

我想出了以下命令,但它会删除所有出现的标签。有没有办法只删除第一次出现,然后将更新的标签插入同一位置

<?xml version="1.0" encoding="utf-8"?>
<Project Toolsversion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">iPhonesimulator</Platform>
    <ProductVersion>8A-0V-W3</ProductVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|iPhonesimulator' ">
    <DebugSymbols>true</DebugSymbols>
    <ProductVersion>PK-0X-SD</ProductVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|iPhonesimulator' ">
    <DebugType>none</DebugType>
    <ProductVersion>SD-AA-SW</ProductVersion>
  </PropertyGroup>

解决方法

使用 Select-Xml cmdlet:

$firstVersion = (
  Select-Xml //ns:ProductVersion test.csproj -Namespace @{ ns='http://schemas.microsoft.com/developer/msbuild/2003' }
)[0].Node

$firstVersion.InnerText = 'A0-B0-C0'

$firstVersion.OwnerDocument.Save((Join-Path $PWD.ProviderPath test1.csproj))
,
$oldValue = "8A-0V-W3";
$newValue = "A0-B0-C0";
$projFile = "./test.csproj";

$config = (Get-Content $projFile) -as [Xml];
$ns = New-Object System.Xml.XmlNamespaceManager($config.NameTable);
$ns.AddNamespace("cs",$config.DocumentElement.NamespaceURI);

$config.DocumentElement.SelectNodes("//cs:ProductVersion",$ns) | % {
    $node = $_;
    if ($node.InnerText -ieq $oldValue) {
        $node.InnerText = $newValue;
    }
}

$config.Save($projFile);