PowerShell script to install Chocolatey and a list of packages
Asked Answered
M

7

27

My goal is to create a single script that I can download and run on a fresh Windows build to set up the system as much as possible. The first thing I am trying to do is install as many of the programs that I always like to have available as possible. I previously ran this (it is from chocolatey.org) to install Chocolatey directly from PowerShell:

Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

Then I ran a bunch of choco installs like this:

choco install googlechrome -y
choco install git -y
choco install notepadplusplus -y
choco install sql-server-management-studio -y

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

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?
  • How do I conditionally run the install command based on that result?
  • How do I loop through a list of packages and run the choco install command on each?

If you have any suggestions on how to accomplish my main goal using other means, please let me know.

Maje answered 8/1, 2018 at 4:7 Comment(0)
P
27

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

(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.

Potman answered 8/1, 2018 at 4:41 Comment(4)
You have some things here which are incorrect, I started to edit the question, but in editing I would be removing the entire bit about Package Management (or moving it to the bottom) as it doesn't apply to the OP's request.Carilyn
I decided to edit than to add a different response as this question was mostly right. The spirit of this community is about fixing to be appropriate, so that's what I did here.Carilyn
I can stipulate to the those conditions.Potman
I'm not sure what you meant, but you haven't reversed my changes so must be good! :DCarilyn
D
7

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 :)

Deodorize answered 7/1, 2019 at 19:0 Comment(0)
S
6

I actually made a batch script which uses the functionality of chocolately itself(config files). You can look it up here. Just change the packages in the config files.

Swadeshi answered 11/9, 2018 at 11:2 Comment(0)
M
6

Here is my answer with a file that contains the list of the packages:

#Requires -RunAsAdministrator

Set-ExecutionPolicy Bypass -Scope Process -Force

# install chocolatey if not installed
if (!(Test-Path -Path "$env:ProgramData\Chocolatey")) {
  Invoke-Expression((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
}

# for each package in the list run install
Get-Content ".\packages" | ForEach-Object{($_ -split "\r\n")[0]} | ForEach-Object{choco install -y $_}

Assuming there is in this path a file named packages with the following content:

googlechrome
git
notepadplusplus
sql-server-management-studio
Maltha answered 15/8, 2019 at 10:2 Comment(1)
How do you run the script though?Kamp
E
4

Let me combine excellent insights from postanote and "How to run a PowerShell script"

Content of home_env_powershell_scr.ps1:

$Packages = 'googlechrome',
            'git'
 
If(Test-Path -Path "$env:ProgramData\Chocolatey") {
  # DoYourPackageInstallStuff
  ForEach ($PackageName in $Packages)
    {
        choco install $PackageName -y
    }
}
Else {
  # InstallChoco
  Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))      

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

Run this script in powershell (checked in version 5):

powershell -executionpolicy bypass -File C:\Users\mypath\home_env_powershell_scr.ps1
Ealing answered 30/11, 2020 at 5:18 Comment(3)
The ForEach should live after the If/Else closes, removing that duplication. Then the conditional can be inverted to check if that path doesn't exist and install choco for that case. No else branch needed.Complicity
Error: choco : The term 'choco' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At C:\Users\sebas\desktop\home_env_powershell_scr.ps1:14 char:2 + choco install $PackageName -y + ~~~~~ + CategoryInfo : ObjectNotFound: (choco:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Kamp
@SebastianNielsen looks like choco is not installed properly: type in Powershell gcm choco. If get the same message, install choco following official guide.Ealing
C
2

A script using Powershell with external packages file (allowing comments that get ignored), plus a dry run:

install-programs.ps1


## To fix "cannot be loaded because running scripts is disabled on this system" (run: 'get-executionpolicy' returns: Restricted) -->
## set-executionpolicy remotesigned

# Run following to bypass "not digitally signed" issue (fixes per session only)
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass

$dryRun = $false;
$packages = 'packages.txt' #'packages-test.txt'

write-host "`n---+++ START powershell script to install packages, using chocolately (`chocolatey.org`) +++---`n"

if($dryRun) {
  write-host "... DRY RUN ONLY ..."
}

$chocoIsInstalled = Test-Path -Path "$env:ProgramData\Chocolatey" # Get-Command choco.exe -ErrorAction SilentlyContinue

if ($chocoIsInstalled) {
  write-host "`n--> Chocolately is already installed ---`n"
}
else {
  write-host "`n--> Chocolately was not installed, let's install it! ---`n"

  if(!$dryRun) {
    write-host "Just kiddin', not gonna install choco"
  }
  else {
    Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
  }
}

$array = (gc $packages) -notmatch '^\s*$' -notmatch '^#' | ? {$_.trim() -ne "" }

foreach($item in $array)
{
  write-host "`n* --> Next package install: '${item}'`n"
  if($dryRun) {
    write-host "Just kiddin', not gonna do it"
  }
  else {
    choco install $item -fy
  }
} 

write-host "`n---+++ FINISH install script +++---`n"

packages.txt (sample, replace)

# browsers
brave
#firefox
#googlechrome 

# Text editors / IDEs
vscode
notepadplusplus

# code
git
Chaconne answered 18/7, 2022 at 2:38 Comment(1)
I'm almost sure I've seen a way to use this type of packages.txt with just boxstarter or chocolatey directly, without an additional script. Anybody know how that would be possible?Allegraallegretto
L
-2

choco install --root
<==== $downloading from https://www.repository.mirror.its.co.id//
<===== loading package...
<==== installing..
<=== $installed

for install chocolatey enter:

@@off
choco feature -on -n .fix.root
installing root...
chocoing...
username: mamas
password: patrakom
loginning...
<=============== downloading choco for windows from https://repository.its.ac.id//choco-installer
installing 7zip-10.45.3.11.0-x64.msi
adding repository from https://mirror.its.ac.id//
<- downloading login packages..]
password: patrakom
packing choco.nupkg
installing...
installed

when open bunch of chocolatey from `mirror.its.hackerindonesia.or.id'

you about install linuxmint_64_xfce4.4_username_Torrent.iso.torrent 
username: mamasdanisy
password: patrakom123
settings: console
partion: chocolatey and c: drive.
are you add for repository this...
installing linux mint xfce...
booting....
saveing windows..
removing windows..
boot uefi booter from apt installer
linuxmint
installing linuxmint...
installed
linuxmint 34.03 lts 
selecting package.logs..
installing linuxmint...
building linuxmint package manually..
null-10-2-999-990 null null null null gawk-root
building linuxmint image...
builded..
installing linuxmint...
installed...
now you boot your choco install and login as mamas danisy and password for user mamas danisy is patrakom123
boot
linux 91.23 lts
[boot] starting service
[boot] starting pidgin with installing...
[boot] maintaining username....
[boot] logging in...
[boot] you are start avahi daemon [y/n] y-
[boot] starting avahi daemon...
[boot] starting linuxmint....
[boot] selecting torrent..
[boot] loading..
[boot] # linux settings [ok] # installing linuxmint [ok]
[boot] installing linuxmint...
[boot] installed.
linuxmint 92.40 text mode login
===============================
username: mamasdanisy
password: patrakom123
installed.
choco install wubi-discontinued
<==== downloading from https://repository.its.ac.id
<===== add link image for wubi manually enter command here: choco manual wubi-discontinued-eof <<echo-root <<echo-root <<installing root... build ubuntu images choco manual ubuntu images..
choco manual build ubuntu images
<======== downloading wubi.exe scripts...
building package wubi.exe from https://repository.its.ac.id//
<=========== installing c:/lib/nupkg/package.logs/wubi.exe/
<=========== packing c:/lib/nupkg/package.logs/wubi.exe/
<============ installing c:/nupkg/package.logs/wubi.exe
<============ installing wubi...
chocolatey has installed 1/1 package manually from repository.its.ac.id

`

Levania answered 27/4, 2020 at 5:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.