PowerShell script to install Chocolatey and a list of packages

Actually Microsoft have been working on a windows-dev-box-setup-scripts to accomplish that, using boxstarter and chocolatey

As an open source project you can fork it or download it and adapt it to your needs

Hope it helps :)


All of your questions could be answered by looking at the PowerShell help files and Microsoft tech documentation:

(Get-Command -Name Test-Path).Parameters
Get-help -Name Test-Path -Examples
Get-help -Name Test-Path -Full
Get-help -Name Test-Path -Online

For loops

  • About For
  • About ForEach
  • PowerShell Loops

(I think the -y makes them run without a prompt.)

Correct, and it should always be used in scripting.

The script should check if Chocolatey is installed and if not, run the install script. Then it should loop through a list of package names and silently install them.

• How do I detect if Chocolatey is already installed?

Use PowerShell to Quickly Find Installed Software

Use the link above - or there is an environment variable set on installation, ChocolateyInstall which is set to C:\ProgramData\Chocolatey by default.

Test-Path -Path "$env:ProgramData\Chocolatey"

A more deterministic way may be to try

$ChocoInstalled = $false
if (Get-Command choco.exe -ErrorAction SilentlyContinue) {
    $ChocoInstalled = $true
}

# Do something with that for installation

• How do I conditionally run the install command based on that result?

Using an if statement:

If(Test-Path -Path "$env:ProgramData\Chocolatey") {
    DoYourPackageInstallStuff}
Else {
    InstallChoco
    DoYourPackageInstallStuff
}

• How do I loop through a list of packages and run the choco install command on each?

Using a for loop:

$Packages = 'googlechrome', 'git', 'notepadplusplus', 'sql-server-management-studio'

ForEach ($PackageName in $Packages)
{
    choco install $PackageName -y
}

Alternative / Enhancement

Microsoft has a built-in package manager manager called PackageManagement (built into PowerShell v5). You can use it with a ChocolateyGet provider (don't use the prototype Chocolatey provider, it is broken and has security issues) for managing third-party dependencies.

The advantage of PackageManagement is that it also has PowerShellGet for managing PowerShell modules.

Just type..

List all available modules / packages

Find-Module

Find-Module -Name SomeSpecificModuleName(s)

For PowerShell version 3 - 4, you have to download and install PowerShellGet.

  • Package Management for PowerShell Modules with PowerShellGet
  • PowerShellGet Module
  • PowerShellGet
  • PowerShell Gallery
  • PowerShellGet