I am creating NuGet package and for that I have created Nuspec manifest file. In content
folder I have two files, test.exe
and test.config
. Now I would like to change property "Copy To Output Directory" of these the files to "Copy Always" in project, when any user installs this package.
I found related question NuGet how to apply properties to files, that shows can do this using PowerShell install.ps1
script, but I have no idea how to create that file.
Your install.ps1 file should look something like this.
param($installPath, $toolsPath, $package, $project)
$file1 = $project.ProjectItems.Item("test.exe")
$file2 = $project.ProjectItems.Item("test.config")
# set 'Copy To Output Directory' to 'Copy if newer'
$copyToOutput1 = $file1.Properties.Item("CopyToOutputDirectory")
$copyToOutput1.Value = 2
$copyToOutput2 = $file2.Properties.Item("CopyToOutputDirectory")
$copyToOutput2.Value = 2
Here is a bit more detail on how to solve this problem end to end:
You need to do two things to ensure the status are set correctly on install...
- Write the install.ps1 script to mark the status of the files.
- Ensure the install.ps1 script is in the Tools directory in the nuget package.
Install.ps1 Script
The following example script will recursively mark every file in the "Content" and "View" directory as "Copy to newer". Note this example script is written to make it clear to read and understand. It will mark every file in the Content and Views folders in the root directory of the Visual Studios project.
param($installPath, $toolsPath, $package, $project)
function MarkDirectoryAsCopyToOutputRecursive($item)
{
$item.ProjectItems | ForEach-Object { MarkFileASCopyToOutputDirectory($_) }
}
function MarkFileASCopyToOutputDirectory($item)
{
Try
{
Write-Host Try set $item.Name
$item.Properties.Item("CopyToOutputDirectory").Value = 2
}
Catch
{
Write-Host RecurseOn $item.Name
MarkDirectoryAsCopyToOutputRecursive($item)
}
}
#Now mark everything in the a directory as "Copy to newer"
MarkDirectoryAsCopyToOutputRecursive($project.ProjectItems.Item("Content"))
MarkDirectoryAsCopyToOutputRecursive($project.ProjectItems.Item("Views"))
Copy To Tools
You must copy the install.ps1 file to the Tools directory for script to be executed by nuget. You can add the following to the nuspec template to do this.
<files>
<file src="install.ps1" target="Tools"/>
</files>
Note in this case I have the install.ps1 file in the root of my Visual Studios project and marked as "Copy if newer".