我正在尝试编写一个NuGet包init.ps1脚本,该脚本将修改.targets文件(XML)的一个值并保存文档。该脚本成功完成所有操作而没有错误,但是当我检查文档时它没有被更改。
这是脚本:
Param($installPath, $toolsPath, $package)
$proj = Get-Project
$pack = $package
# Detect if the project installing the NuGet package is a web application and
# alters an xml element value in the .targets value to prevent duplication
# of application resources when published.
if ($proj.ExtenderNames -contains "WebApplication") {
# Begin to build neccessary path strings to find the .targets file.
# The targets file is currently located in
# \packages\packageName.packageVersion\build\packageName.targets.
$packageName = [string]$pack.Id
$packageRootDir = $installPath
# packageName.Version\build
$packageBuildFolderPath = Join-Path $packageRootDir "build"
# packageName.Version\build\packageName
$targetsFilePath = Join-Path $packageBuildFolderPath ($packageName + ".targets")
"$targetsFilePath"
if (Test-Path $targetsFilePath) {
# If the targets file path has correctly located the file then
# we edit the targets file to alter the CopyToOutputDirectory element.
# Load the targets file as an xml object
$xml = New-Object System.Xml.XmlDocument
$xml.Load($targetsFilePath)
"xml loaded"
# Search each ItemGroup element for the one containing a Content element.
foreach ($group in $xml.Project.ItemGroup) {
$nodeExists = $group.Content.CopyToOutputDirectory
if ($nodeExists) {
"$nodeExists"
# Edits the value when we find the correct node
$nodeExists = "Never"
"$nodeExists"
}
}
"xml modified"
# Save the updated document to the correct place.
$savePath = [string]$targetsFilePath
"$savePath"
$xml.Save($savePath)
"xml Saved to $savePath"
}
}
以下是脚本块开头到结尾的包管理器输出:
Executing script file 'path to tools/Init.ps1' 'correct path to package/build/package.targets' xml loaded Always Never xml modified 'correct path to package/build/package.targets' xml Saved to 'correct path to package/build/package.targets'
答案 0 :(得分:1)
您的代码会修改变量$nodeExists
的值,但不会修改值来自的XML节点。您可以通过查看循环后的实际XML数据来验证:
$xml.Save([Console]::Out)
要实际修改节点的值,请将代码更改为:
foreach ($group in $xml.Project.ItemGroup) {
if ($group.Content.CopyToOutputDirectory) {
$group.Content.CopyToOutputDirectory = 'Never'
}
}
或者像这样:
$xml.SelectNodes('//Content/CopyToOutputDirectory') | ForEach-Object {
$_.'#text' = 'Never'
}
请注意,如果您的XML使用名称空间,后者需要namespace manager。