A Simple PowerShell Script for Installing Chocolatey

For IT professionals and Managed Service Providers (MSPs) charged with managing multiple systems, software installation can be a major time-suck. Utilizing package managers like Chocolatey can be a game changer. Yet, ensuring Chocolatey itself is installed or up to date can also pose a challenge. To streamline this process, we have designed a PowerShell script that makes installing and upgrading Chocolatey — and consequently, your desired applications — effortless.

What is Chocolatey?

Chocolatey is a machine-level, command-line package manager for Windows that simplifies the process of managing software installations. With Chocolatey, you can install, upgrade, configure, and uninstall software with a few simple commands, thereby automating processes and eliminating the need for manual interventions.

Chocolatey Install Script

#Requires -Version 5.1

<#
.SYNOPSIS
    Install an application with Chocolatey. This can install and upgrade Chocolatey before install an application.
.DESCRIPTION
    Install an application with Chocolatey. This can install and upgrade Chocolatey before install an application.
.EXAMPLE
     -Name "git"
    Installs git via Chocolatey.
    If Chocolatey isn't installed this downloads and uses 7zip to extract Chocolatey's install zip file.
.EXAMPLE
     -Name "git" -TimeOut 10
    Installs git via Chocolatey.
    If Chocolatey isn't installed this downloads and uses 7zip to extract Chocolatey's install zip file.
    If the install takes more than 10 minutes, exit the script with an error.
.EXAMPLE
     -Name "git" -InstallUri "https://community.chocolatey.org/install.ps1"
    Installs git via Chocolatey.
    Uses a custom URL to download the Chocolatey install script.
    If Chocolatey isn't installed this downloads and uses 7zip to extract Chocolatey's install zip file.
.EXAMPLE
     -Name "git" -Upgrade
    Installs git via Chocolatey.
    Runs the upgrade command for Chocolatey to attempt to upgrade Chocolatey.
    If Chocolatey isn't installed this downloads and uses 7zip to extract Chocolatey's install zip file.
.EXAMPLE
     -Name "git" -UseNativeUnzip
    Installs git via Chocolatey.
    If Chocolatey isn't installed this does not downloads and use 7zip to extract Chocolatey's install zip file.
.OUTPUTS
    String[]
.NOTES
    Minimum OS Architecture Supported: Windows 10, Windows Server 2016
    Release Notes:
    Initial Release
    (c) 2023 NinjaOne
    By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#>

[CmdletBinding()]
param (
    [Parameter()]
    [String]
    $Name,
    [Parameter()]
    [String]
    $InstallUri = "https://community.chocolatey.org/install.ps1",
    [Parameter()]
    [ValidateRange(1, 60)]
    [int]
    $TimeOut = 5,
    [Parameter()]
    [Switch]
    $UseNativeUnzip,
    [Parameter()]
    [Switch]
    $Upgrade
)

begin {
    function Test-ChocolateyInstalled {
        [CmdletBinding()]
        param()
    
        $checkPath = if ($env:ChocolateyInstall) { $env:ChocolateyInstall } else { "$env:PROGRAMDATAchocolatey" }
        $Command = Get-Command choco.exe -ErrorAction Ignore

        if ($Command.Path -and (Test-Path -Path $Command.Path)) {
            # choco is in the %PATH% environment variable, assume it's installed
            Write-Warning "'choco' was found at '$($Command.Path)'."
            $true
        }
        elseif (-not (Test-Path $checkPath)) {
            # Install folder doesn't exist
            $false
        }
        elseif (-not (Get-ChildItem -Path $checkPath)) {
            # Install folder exists but is empty
            $false
        }
        else {
            # Install folder exists and is not empty
            Write-Warning "Files from a previous installation of Chocolatey were found at '$($CheckPath)'."
            $true
        }
    }
}
process {
    if (-not $(Test-ChocolateyInstalled)) {
        # Install Chocolatey
        Write-Host "Chocolatey not installed."
        Write-Host "Installing Chocolatey."
        [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072
        $ChocolateyScript = [scriptblock]::Create($(Invoke-RestMethod -Uri $InstallUri))
        try {
            if ($UseNativeUnzip) {
                $ChocolateyScript.Invoke(@("-UseNativeUnzip"))
            }
            else {
                $ChocolateyScript.Invoke()
            }
            Write-Host "Installed Chocolatey."
        }
        catch {
            Write-Error $_
            Write-Host "Failed to install Chocolatey."
            exit 1
        }
    }

    # Upgrade Chocolatey
    if ($Upgrade) {
        choco.exe upgrade chocolatey --yes --nocolor --limitoutput --no-progress
        $ExitCode = $LASTEXITCODE
    
        if ($ExitCode -eq 0) {
            Write-Host "Chocolatey Upgraded."
        }
        elseif ($ExitCode -ne 0) {
            Write-Error "Failed to upgrade Chocolatey."
            Write-Host "Installer returned exit code: $($ExitCode)"
            exit 1
        }
    }

    # Install Application
    choco.exe install $Name --yes --nocolor --limitoutput --no-progress
    $ExitCode = $LASTEXITCODE
    
    if ($ExitCode -eq 0) {
        Write-Host "Installed $Name"
        exit 0
    }
    elseif ($ExitCode -ne 0) {
        Write-Error "Failed to install $Name."
        Write-Host "Installer returned exit code: $($ExitCode)"
        exit 1
    }
    
    Write-Host "Installed $Name."
}
end {}

PowerShell Script Parameters and Their Uses

Our PowerShell script accepts several parameters that can control its operation:

  1. Name: Specifies the name of the application you want to install.
  2. InstallUri: Allows you to use a custom URL to download the Chocolatey install script. The default is the official Chocolatey install script URL.
  3. TimeOut: This is the maximum time, in minutes, that the script will wait for an operation to complete before aborting. The default value is 5 minutes.
  4. UseNativeUnzip: A switch that, if included, will use the native Windows utility to unzip the Chocolatey install file.
  5. Upgrade: A switch that, if included, will upgrade Chocolatey to the latest version before installing the application.

Installation Examples

Here are a few examples of how to use the script to install different types of software:

To install Git, use:

powershell 
  -Name "git" 

To install Visual Studio Code with a custom timeout of 15 minutes, use:

powershell 
  -Name "visualstudiocode" -TimeOut 15 

To install Node.js and upgrade Chocolatey before the installation, use:

powershell 
  -Name "nodejs" -Upgrade 

Security Considerations

While the script can simplify the installation process, it’s crucial to consider the security implications. The script downloads and installs software from the internet, so you must ensure the source’s integrity.

By default, the script uses the official Chocolatey install script URL, a reliable and secure source. However, if you use the ‘InstallUri’ parameter to specify a custom URL, ensure it’s a trustworthy and safe source.

Moreover, the script will execute with the permissions of the user running it, so be mindful of the rights you grant. Ideally, use a user with the minimum required permissions to mitigate potential security risks.

In conclusion, our PowerShell script offers a streamlined, efficient way to install Chocolatey on Windows. It’s flexible and can be tailored to your needs, making it an indispensable resource for IT professionals and MSPs alike. By using PowerShell to install Chocolatey, you can improve workflows, enhance efficiency, and increase your productivity, while also reducing the likelihood of errors.

Access this script and hundreds more within NinjaOne.

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

Watch Demo×
×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).