I have a Powershell script (run by my NuGet package) that adds a post build event to a user's Visual Studio project.
$project.Properties | where { $_.Name -eq "PostBuildEvent" } | foreach { $_.Value = "xcopy `"`$(ProjectDir)MyFolder`" `"`$(OutDir)`"" }
Unfortunately it currently overwrites the existing post build event. How can I modify the Powershell script to append my build event if it does not already exist?
I've never used Powershell before but I tried simply appending it inside the foreach, but this didn't work:
$_.Value = "$_.Value`nxcopy `"`$(ProjectDir)MyFolder`" `"`$(OutDir)`""
just gives:
System.__ComObject.Value xcopy "$(ProjectDir)MyFolder" "$(OutDir)"
I think editing the PostBuildEvent property is the wrong way to go about adding a post build action to a user's project. I believe the recommended way is to put your custom action into a target that is then imported into the project file. As of NuGet 2.5 if you include a 'build' folder in your package (at the same level as content and tools) and it contains a {packageid}.targets file or {packageid}.props file, NuGet will automatically add an Import to the project file when you install the package.
For example you have a package called MyNuGet. You create a file build\MyNuGet.targets
containing:
<?xml version="1.0" encoding="utf-8" ?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<MySourceFiles Include="$(ProjectDir)MyFolder\**" />
</ItemGroup>
<Target Name="MyNuGetCustomTarget" AfterTargets="Build">
<Copy SourceFiles="@(MySourceFiles)" DestinationFolder="$(OutDir)" />
</Target>
</Project>
This creates a custom target that is configured to run after the standard Build target. It will copy some files to the output directory.
You do not need to do anything else in install.ps1. When the user installs your package, NuGet will automatically add an Import to the user's proj files and your target will run after the Build target is run.
When inside quotes, and referencing variables with properties, you have to enclose them in a $()
so this:
$_.Value = "$_.Value`nxcopy `"`$(ProjectDir)MyFolder`" `"`$(OutDir)`""
should be this:
$_.Value = "$($_.Value)`nxcopy `"`$(ProjectDir)MyFolder`" `"`$(OutDir)`""
or the simpler method is to use a +=
i.e:
$_.Value += "`nxcopy `"`$(ProjectDir)MyFolder`" `"`$(OutDir)`""
来源:https://stackoverflow.com/questions/25510584/add-post-build-event-without-overwriting-existing-events