问题描述
我想通过 NuGet 包将解决方案文件夹和解决方案项(不是项目)添加到解决方案文件.我想这将通过 Powershell 来完成.我查看了 NuGet、Powershell 和 EnvDTE 的文档,但无法弄清楚:
I want to add solution folders and solution items (not projects) to a solution file via a NuGet package. I imagine this would be accomplished through Powershell. I've looked through the documentation for NuGet, Powershell, and EnvDTE and can't figure out:
- 我会使用哪些命令/方法?
- 我会在哪个标准脚本中执行此操作,Init.ps1、Install.ps1 还是其他地方?
推荐答案
这是一个 PowerShell 脚本,它将创建一个名为 Parent 的解决方案文件夹和另一个名为 Child 的解决方案文件夹.它还在子解决方案文件夹中添加了一个项目文件 (MyProject.csproj).
Here is a PowerShell script that will create a solution folder called Parent and another solution folder called Child inside that one. It also adds a project file (MyProject.csproj) inside the Child solution folder.
# Get the open solution.
$solution = Get-Interface $dte.Solution ([EnvDTE80.Solution2])
# Create the parent solution folder.
$parentProject = $solution.AddSolutionFolder("Parent")
# Create a child solution folder.
$parentSolutionFolder = Get-Interface $parentProject.Object ([EnvDTE80.SolutionFolder])
$childProject = $parentSolutionFolder.AddSolutionFolder("Child")
# Add a file to the child solution folder.
$childSolutionFolder = Get-Interface $childProject.Object ([EnvDTE80.SolutionFolder])
$fileName = "D:projectsMyProjectMyProject.csproj"
$projectFile = $childSolutionFolder.AddFromFile($fileName)
这里使用的两个主要 Visual Studio 界面是 Solution2 和SolutionFolder.它还使用了 NuGet 提供的 Get-Interface 函数.
The two main Visual Studio interfaces being used here are Solution2 and SolutionFolder. It also uses the Get-Interface function which is provided by NuGet.
对于仅解决方案包,您应该将脚本放在 init.ps1 中,因为 install.ps1 仅对基于项目的包调用.Init.ps1 在首次安装包时为解决方案运行一次,并且每次在 Visual Studio 中重新打开解决方案时.
For a solution-only package you should place your script in init.ps1 because install.ps1 is only invoked for project-based packages. Init.ps1 runs once for a solution when the package is first installed and every time the solution is re-opened in Visual Studio.
要将任意文件(非项目文件)添加到解决方案文件夹,您需要执行类似以下操作:
To add arbitrary files (non-project files) to a solution folder you will need to do something similar to the following:
$vsSolution = Get-Interface $dte.Solution ([EnvDTE80.Solution2])
$vsProject = $vsSolution.AddSolutionFolder("newFolder")
$projectItems = Get-Interface $vsProject.ProjectItems ([EnvDTE.ProjectItems])
$projectItems.AddFromFile("pathToFileToAdd.txt")
此 PowerShell 脚本中缺少的是文件顶部的标准参数声明.
What is missing from this PowerShell script is the standard parameter declarations at the top of file.
param($installPath, $toolsPath, $package, $project)
还缺少检查解决方案文件夹和文件夹项是否已存在.我将把它留给你做练习.
What is also missing is checking whether the solution folder and folder item already exist. I shall leave that as an exercise for you to do.
这篇关于在 NuGet 包中添加解决方案级项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!