Add code analysis ruleset through nuget package

There's no need to script this. Both the ruleset and dictionary can be registered via an imported MSBuild .props file, as described here https://learn.microsoft.com/en-us/nuget/create-packages/creating-a-package#include-msbuild-props-and-targets-in-a-package

For example, your NuGet source folder structure might look like this (assuming "CodeAnalysisSettings" is your package ID):

  • build
    • CodeAnalysisSettings.props
  • content
    • MyCustomDictionary.xml
    • MyRules.ruleset

where the contents of CodeAnalysisSettings.props are something like the following:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <PropertyGroup>
        <RunCodeAnalysis>true</RunCodeAnalysis>
        <CodeAnalysisRuleSet>MyRules.ruleset</CodeAnalysisRuleSet>
    </PropertyGroup>
    <ItemGroup>
        <CodeAnalysisDictionary Include="MyCustomDictionary.xml" />
    </ItemGroup>
</Project>

I had the same problem as reported in the comments: the dictionary was added as content, not as a CodeAnalysisDictionary.

I added this piece of code in the install.ps1 of the nuget package to solve this:

$dictionary = $project.ProjectItems | Where-Object {$_.Name.EndsWith("CustomDictionary.xml")}
$dictionary.Properties.Item("Buildaction").Value = [int]5;