NuGet:是否可以通过 Powershell 添加一行代码? [英] NuGet: Possibility of adding a line of code via Powershell?

查看:52
本文介绍了NuGet:是否可以通过 Powershell 添加一行代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将一些 NuGet 包放在一起,其中一个是所有其他包都引用的通用项目.

I have a few NuGet packages that I've put together, with one of them being a common project referenced by all the others.

这个普通项目在App_Start文件夹中插入一个配置类,然后WebActivator调用这个类上的一个方法.

This common project inserts a configuration class into the App_Start folder, and a method on this class is then invoked by WebActivator.

对于其他包之一,我希望在此方法中再添加一行代码,但我正在努力寻找一种方法来做到这一点.

For one of the other packages I wish to add one more line of code to this method but I'm struggling to find a way to do this.

我知道我可以非常简单地添加一个仅包含这一行代码的附加类,但如果可能的话,我更喜欢使用 Install.ps1 PowerShell 脚本来添加该行代码到现有的配置类.

I know that I could very simply add an additional class which contains just this one line of code but I'd prefer, if possible, to use an Install.ps1 powershell script to add the line of code to the existing configuration class.

使用经过预处理的 *.cs.pp 文件将覆盖现有文件(或添加新文件),而 *.cs.transform 不会处理这样的文件.

Using a pro-processed *.cs.pp file will overwrite the existing file (or add a new one), and *.cs.transform doesn't work on such a file.

我知道这个类在哪里,它叫什么,我知道这个方法叫什么,那么 Powershell 是否提供了一种在所述方法的末尾添加一行的方法?

I know where the class is and what it's called, and I know what the method is called, so does Powershell offer a means of adding a line to the end of said method?

推荐答案

这是可能的,但并非微不足道.您还必须非常小心,因为从 NuGet 包中删除某人的代码不会让他们非常高兴.

This is possible but not trivial to do. You also have to be very careful since deleting someone's code from a NuGet package is not going to make them very happy.

安装 NuGet 包时,您可以访问 Visual Studio 对象模型 (EnvDTE).$project 变量可用于访问您需要的特定项目项.从中您可以使用 FileCodeModel 表示文件.然后,您需要找到该类及其方法.然后创建一个编辑点并插入文本.

When installing a NuGet package you have access to the Visual Studio object model (EnvDTE). The $project variable can be used to access the specific project item you need. From that you can use the FileCodeModel which represents the code in the file. You would then need to find the class and its method. Then create an edit point and insert the text.

下面会找到一个名为Class1的类,并在其Foo方法中插入一行代码.请注意,插入的代码行不会正确缩进,您需要查看文档才能找到.

The following will find a class called Class1 and insert a line of code into its Foo method. Note that the line of code inserted will not be correctly indented, you would need to find that out by looking at the document.

$project.ProjectItems.Item("Class1.cs")
$namespace = $item.FileCodeModel.CodeElements | ? {$_.Kind -eq 5}
$namespace.Members.Item("Class1")
$method = $class.Members.Item("Foo")
$endPoint = $method.GetEndpoint([EnvDTE.vsCMPart]::vsCMPartBody)
$editPoint = $endpoint.CreateEditPoint()
$editPoint.Insert("int a = 0;")

上述代码也没有做任何错误处理.

Also the above code does not do any error handling.

这篇关于NuGet:是否可以通过 Powershell 添加一行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆