如何在NuGet包安装期间获取文件的内容

时间:2018-05-01 12:40:04

标签: nuget-package powershell-v5.0

我有一个nuget包解决方案安装得很好。我现在需要修改目标项目的Properties\AssemblyInfo.cs文件以添加一些代码。

我有一个Install.ps1脚本,所以我将我的powershell脚本添加到此。当我正在建立它时,它目前所做的是:

param($installPath, $toolsPath, $package, $project)
$content = Get-Content $project.ProjectItems.Item("Properties\AssemblyInfo.cs")

它给我的错误是:

Value does not fall within the expected range.At 
C:\git\Testing\packages\Standards.Testing.1.0.6694.30974-beta\tools\Install.ps1:2
char:1
+ $content = Get-Content $project.ProjectItems.Item("Properties\Assembl ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException

目的是加载AssemblyInfo.cs文件的内容并检查其中的某些内容,然后对其进行修改并将其写回。

我不明白为什么它不会将该文件的内容读入变量。

1 个答案:

答案 0 :(得分:1)

问题是我错误地尝试引用AssemblyInfo.cs文件的路径。我没有意识到脚本的参数提供了我需要的一切,其他帖子引用了一个可怕的类,其中包含所有必需的信息。

包含有关脚本参数的信息: Need PowerShell Script in NuGet to install selected DLLs from Package into a VS Project

该帖子链接的是此页面,其中详细介绍了有关nuget安装的可用信息: https://docs.microsoft.com/en-us/dotnet/api/envdte.dte?redirectedfrom=MSDN&view=visualstudiosdk-2017

我的脚本现在看起来像这样:

param($installPath, $toolsPath, $package, $project)

#Update the AssemblyInfo.cs if it has not been updated before
function Get-Append-String {
    $text = ''
    $args[0] | ForEach-Object -Process {
        $text += $_ + "`n"
    }
    return $text
}

function Get-Append {
    $text = ''
    $args | ForEach-Object -Process {
        $text += $_
    }
    return $text
}

function Get-Contains {
    $text = Get-Append-String $args[0]
    return ($text -like $args[1])
}

$query = "*using Xunit;*"
$xunit = "using Xunit;`n"
$comment = "`n// xUnit configuraiton...`n// MaxParallelThreads limits the number of threads which xUnit will use to run tests`n[assembly: CollectionBehavior(MaxParallelThreads = 8)]`n"

$path = $project.FullName + '\..\Properties\AssemblyInfo.cs'
$content = Get-Content -Path $path
$content = Get-Append-String $content

if ( ($content -like $query) -eq $false ) {
    $content = $xunit + $content + $comment
    Set-Content -Path $path -Value $content
}