How to add an MSBuild import to a project on NuGet install

This functionality has been discussed and requested as a feature for a future version of NuGet.

While this gets into the core of NuGet, you can use this code in an install.ps1 script (see Automatically Running PowerShell Scripts During Package Installation and Removal section if you don’t know what that file is for):

param($installPath, $toolsPath, $package, $project)
    # This is the MSBuild targets file to add
    $targetsFile = [System.IO.Path]::Combine($toolsPath, 'Funq.Build.targets')

    # Need to load MSBuild assembly if it's not loaded yet.
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Build") | out-null
    # Grab the loaded MSBuild project for the project
    $msbuild = [Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection.GetLoadedProjects($project.FullName) | Select-Object -First 1
    
    # Make the path to the targets file relative.
    $projectUri = new-object Uri('file://' + $project.FullName)
    $targetUri = new-object Uri('file://' + $targetsFile)
    $relativePath = $projectUri.MakeRelativeUri($targetUri).ToString().Replace([System.IO.Path]::AltDirectorySeparatorChar, [System.IO.Path]::DirectorySeparatorChar)
    
    # Add the import and save the project
    $msbuild.Xml.AddImport($relativePath) | out-null
    $project.Save()...

Read full article

No Comments