Add post-build event without overwriting existing events

I have a Powershell script (executed by my NuGet package) that adds a post build event to a custom Visual Studio project.

$project.Properties | where { $_.Name -eq "PostBuildEvent" } | foreach { $_.Value = "xcopy `"`$(ProjectDir)MyFolder`" `"`$(OutDir)`"" }

      

Unfortunately it is currently overwriting the existing post build event. How can I change the PowerShell script event to append if it doesn't already exist?

I've never used Powershell before, but I tried just adding it inside foreach, but it didn't work:

$_.Value = "$_.Value`nxcopy `"`$(ProjectDir)MyFolder`" `"`$(OutDir)`""

      

just gives:

System .__ ComObject.Value xcopy "$ (ProjectDir) MyFolder" "$ (OutDir)"

+3


source to share


2 answers


I think editing the PostBuildEvent property is the wrong way to add a post build action to a custom project. I believe the recommended way is to put your custom actions in a target, which is then imported into the project file. Since NuGet 2.5 , if you have included a "build" folder in your package (content and tool level) and it contains a {packageid} .targets file or {packageid} .props file, NuGet will automatically add 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 configured to run after a standard build. It will copy some files to the output directory.

You don't need to do anything in install.ps1. When the user installs your package, NuGet will automatically add Import to the custom proj files and your target will be launched after the build object is run.

+5


source


When inside quotes and refers to variables with properties, you must enclose them in $()

so that:

$_.Value = "$_.Value`nxcopy `"`$(ProjectDir)MyFolder`" `"`$(OutDir)`""

      

should be as follows:



$_.Value = "$($_.Value)`nxcopy `"`$(ProjectDir)MyFolder`" `"`$(OutDir)`""

      

or an easier way is to use +=

i.e:

$_.Value += "`nxcopy `"`$(ProjectDir)MyFolder`" `"`$(OutDir)`""

      

+1


source







All Articles