Create a custom powershell script for nuget that adds a custom target to the csproj BeforeBuild step

前端 未结 2 1036
终归单人心
终归单人心 2020-12-28 08:50

I want to create a nuget package that adds a BeforeBuild step to my csproj using a custom MSBuild task I have created. Ideally, I want to:

  1. Add a new Target int
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-28 09:19

    The following code comes from a package called CodeAssassin.WixWebProjectReferences. It adds and removes the following import-tag to the project file upon install and uninstall. The package does not require any dependencies.

    
    

    Download the package and open it using NuGetPackageExplorer to se how it's done.

    Below is the code from install.ps1 and uninstall.ps1 (they are only executed if the content folder of the NuGet-package is non-empty).

    (I couldn't find any powershell-highlighting so I used php instead and it's not perfect.)

    install.ps1

    param (
        $InstallPath,
        $ToolsPath,
        $Package,
        $Project
    )
    
    $TargetsFile = 'CodeAssassin.WixWebProjectReferences.targets'
    $TargetsPath = $ToolsPath | Join-Path -ChildPath $TargetsFile
    
    Add-Type -AssemblyName 'Microsoft.Build, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
    
    $MSBProject = [Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection.GetLoadedProjects($Project.FullName) |
        Select-Object -First 1
    
    $ProjectUri = New-Object -TypeName Uri -ArgumentList "file://$($Project.FullName)"
    $TargetUri = New-Object -TypeName Uri -ArgumentList "file://$TargetsPath"
    
    $RelativePath = $ProjectUri.MakeRelativeUri($TargetUri) -replace '/','\'
    
    $ExistingImports = $MSBProject.Xml.Imports |
        Where-Object { $_.Project -like "*\$TargetsFile" }
    if ($ExistingImports) {
        $ExistingImports | 
            ForEach-Object {
                $MSBProject.Xml.RemoveChild($_) | Out-Null
            }
    }
    $MSBProject.Xml.AddImport($RelativePath) | Out-Null
    $Project.Save()
    

    uninstall.ps1

    param (
        $InstallPath,
        $ToolsPath,
        $Package,
        $Project
    )
    
    $TargetsFile = 'CodeAssassin.WixWebProjectReferences.targets'
    
    Add-Type -AssemblyName 'Microsoft.Build, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
    
    $MSBProject = [Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection.GetLoadedProjects($Project.FullName) |
        Select-Object -First 1
    
    $ExistingImports = $MSBProject.Xml.Imports |
        Where-Object { $_.Project -like "*\$TargetsFile" }
    if ($ExistingImports) {
        $ExistingImports | 
            ForEach-Object {
                $MSBProject.Xml.RemoveChild($_) | Out-Null
            }
        $Project.Save()
    }
    

    Sample targets-file that copies some files to the output path

    
    
        
            
        
        
            
        
    
    

提交回复
热议问题