Previously I’ve been using Ruby and Rake to restore missing NuGets in my Visual Studio solutions. But I’m on a mission to make some of my projects less dependent on stuff other than the “Microsoft environment” so I’m replacing it for a simple PowerShell script which is what this post is about.
But why not use the NuGet package restore?
Simple, I don’t like it. I don’t want to checkin NuGet.exe and I certainly don’t want something simple as restoring NuGets to affect my build files. In my local environment, it’s a one time task per repository, and in my CI environments, I can script this (as you will see). What I really would like to see is:
nuget.exe --restore "some/**/path"
which would search for package.config
files and install any missing NuGets.
What’s wrong with the Rake version
Well, nothing. It’s just that all “.Net devs” don’t have Ruby and Rake installed so in that sense, I think PowerShell works better. I’ve been blogging about Rake and builds before, so I’m just going to include the script here:
task :default => [:installNuGetPackages]
task :installNuGetPackages do
FileList["src/**/packages.config"].each { |filepath|
sh "NuGet.exe i #{filepath} -o src/packages"
}
end
Straight forward an simple. Now lets have a look at the PowerShell script:
PowerShell
Lets first have a look at something that is similar in functionality and then look at one that is a bit more verbose when it comes to providing status information to the user.
Get-ChildItem "src" -Filter "packages.config" -Recurse|
ForEach-Object {
nuget i ""$($_.FullName)"" -o "srcpackages"
}
Does the work and is easy to understand. But before closing the case, lets have a look at the final product, a simple file e.g. setup-devenev.ps1
Function OutPut ($v) {
Write-Host $v -ForegroundColor Cyan
}
Function Install-Packages($basePath) {
OutPut "Installing missing NuGet packages..."
$c = 0
Get-ChildItem $basePath -Filter "packages.config" -Recurse |
ForEach-Object {
OutPut "Installing packages for: '$($_.FullName)'"
nuget i ""$($_.FullName)"" -o "$($basePath)packages"
$c += 1
}
OutPut "Processed $($c) package(s).config."
}
Install-Packages("src")
This would be invoked:
ps:> .setup-devenv.ps1
or
cmd:> powershell -executionpolicy unrestricted .setup-devenv.ps1
That’s it. Now. Case closed.
//Daniel