jack89
jack89

Reputation: 11

Run PowerShell script after NuGet install

I am trying to edit the <Reference> XML node of the currently installing NuGet package library in the csproj via PowerShell to add a Condition="..." attribute.

I was able to call my PowerShell Install.ps1 script during the package's installation but the <Reference> node is not present at that moment.

If I manually add the desired Condition="..." attribute to the csproj it gets removed when updating the NuGet package.

Is there a way to automatically run a PowerShell script after NuGet adds the <Reference> node of the installed library? Or a way to somehow modify the node that NuGet adds when installing the package?

Upvotes: 1

Views: 1362

Answers (2)

jack89
jack89

Reputation: 11

I haven't had time to implement Keith Hill's solution and had to settle on calling my script manually via a batch file. Here is the PowerShell script in case it helps someone.

The goal is to exclude the reference to MyPackageName when in Debug from all projects starting with MyProjectName.

# Get a list of matching csproj files recursively
$csprojs = gci $PSScriptRoot -rec -include MyProjectName.*.csproj

# The value of the condition attribute we want to set
$condition = @'
'$(Configuration)' != 'Debug'
'@

foreach ($csproj in $csprojs)
{
    [xml]$xml = Get-Content $csproj;
    foreach ($reference in $xml.Project.ItemGroup.Reference | ? { $_.Include -match '^MyPackageName' })
    {
        $reference.SetAttribute('Condition', $condition);
    }

    $xml.Save($csproj);
}

Upvotes: 0

Keith Hill
Keith Hill

Reputation: 201632

One option is to not have NuGet add the references by default. Remove your lib folder and put the assemblies elsewhere in the package (refs?). Create a {NuGetPkgName}.targets file and put that in the packages build folder. That targets file will get "imported" into any project you add the NuGet pkg to. Then in your targets file you can add the references to your assemblies with the condition attributes you want.

Upvotes: 1

Related Questions