用于更改csproj文件中的值的Powershell脚本
我想更改下面test.csproj文件中ProductVersion标记的值。我只需要将ProductVersion:8A-0V-W3第一次出现的值更改为A0-B0-C0用于更改csproj文件中的值的Powershell脚本,powershell,scripting,Powershell,Scripting,我想更改下面test.csproj文件中ProductVersion标记的值。我只需要将ProductVersion:8A-0V-W3第一次出现的值更改为A0-B0-C0 <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schema
<?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>
使用cmdlet:
两个旁白:.NET的工作目录通常不同于PowerShell,因此您应该始终向.NET方法调用传递完整路径。用于将相对路径转换为完整路径,前提是该路径已存在。有关更多信息,请参阅
获取内容通常不是用于XML文件的正确命令,因为它(在没有BOM的情况下)将采用默认编码,而不是在给定文件的声明中采用潜在的特定编码(例如,
)。安全的方法是使用$xmlDoc=[xml]::new()
,然后是$xmlDoc.Load('/full/path/to/some.xml')
-需要使用完整路径。如果您碰巧知道Get Content
在给定的情况下使用是安全的,那么您可以使用$xmlDoc=[xml](Get Content-Raw some.xml)
-注意-Raw
以提高性能。是否有办法应用相同的命令只修改以下文件中的一个字符串标记,例如,将com.ab c.com的值更改为com.def.com,而不使用前面命令中指定发生次数时使用的数组-因为文件可能会更新到MinimumOSVersion 12.0 CbundleDisplayName mycompanyy CbundleIdentifier com.abc.com CbundleVersion 1.0.1 CbundleShortVersionString 1。0@ninja666,您将需要类似于selectstring'//String[.=“com.abc.com”]'some.xml的内容。如果您需要进一步帮助,请提出新问题;一旦你这样做了,请随时通知我。
get-content ./test.csproj | select-string -pattern 'ProductVersion' -notmatch | Out-File ./test1.csproj
$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);