Unpacking Software Livestream

Join our monthly Unpacking Software livestream to hear about the latest news, chat and opinion on packaging, software deployment and lifecycle management!

Learn More

Chocolatey Product Spotlight

Join the Chocolatey Team on our regular monthly stream where we put a spotlight on the most recent Chocolatey product releases. You'll have a chance to have your questions answered in a live Ask Me Anything format.

Learn More

Chocolatey Coding Livestream

Join us for the Chocolatey Coding Livestream, where members of our team dive into the heart of open source development by coding live on various Chocolatey projects. Tune in to witness real-time coding, ask questions, and gain insights into the world of package management. Don't miss this opportunity to engage with our team and contribute to the future of Chocolatey!

Learn More

Calling All Chocolatiers! Whipping Up Windows Automation with Chocolatey Central Management

Webinar from
Wednesday, 17 January 2024

We are delighted to announce the release of Chocolatey Central Management v0.12.0, featuring seamless Deployment Plan creation, time-saving duplications, insightful Group Details, an upgraded Dashboard, bug fixes, user interface polishing, and refined documentation. As an added bonus we'll have members of our Solutions Engineering team on-hand to dive into some interesting ways you can leverage the new features available!

Watch On-Demand
Chocolatey Community Coffee Break

Join the Chocolatey Team as we discuss all things Community, what we do, how you can get involved and answer your Chocolatey questions.

Watch The Replays
Chocolatey and Intune Overview

Webinar Replay from
Wednesday, 30 March 2022

At Chocolatey Software we strive for simple, and teaching others. Let us teach you just how simple it could be to keep your 3rd party applications updated across your devices, all with Intune!

Watch On-Demand
Chocolatey For Business. In Azure. In One Click.

Livestream from
Thursday, 9 June 2022

Join James and Josh to show you how you can get the Chocolatey For Business recommended infrastructure and workflow, created, in Azure, in around 20 minutes.

Watch On-Demand
The Future of Chocolatey CLI

Livestream from
Thursday, 04 August 2022

Join Paul and Gary to hear more about the plans for the Chocolatey CLI in the not so distant future. We'll talk about some cool new features, long term asks from Customers and Community and how you can get involved!

Watch On-Demand
Hacktoberfest Tuesdays 2022

Livestreams from
October 2022

For Hacktoberfest, Chocolatey ran a livestream every Tuesday! Re-watch Cory, James, Gary, and Rain as they share knowledge on how to contribute to open-source projects such as Chocolatey CLI.

Watch On-Demand

Downloads:

374,215

Downloads of v 0.0.4:

310,039

Last Update:

15 Sep 2021

Package Maintainer(s):

Software Author(s):

  • Teknowledgist and Bill Curran

Tags:

fonthelp font helper unofficial extension add-font remove-font bcurran3

Chocolatey Font Helpers Extension

  • 1
  • 2
  • 3

0.0.4 | Updated: 15 Sep 2021

Downloads:

374,215

Downloads of v 0.0.4:

310,039

Maintainer(s):

Software Author(s):

  • Teknowledgist and Bill Curran

Chocolatey Font Helpers Extension 0.0.4

Legal Disclaimer: Neither this package nor Chocolatey Software, Inc. are affiliated with or endorsed by Teknowledgist and Bill Curran. The inclusion of Teknowledgist and Bill Curran trademark(s), if any, upon this webpage is solely to identify Teknowledgist and Bill Curran goods or services and not for commercial purposes.

  • 1
  • 2
  • 3

All Checks are Passing

3 Passing Tests


Validation Testing Passed


Verification Testing Passed

Details

Scan Testing Successful:

No detections found in any package files

Details
Learn More

Deployment Method: Individual Install, Upgrade, & Uninstall

To install Chocolatey Font Helpers Extension, run the following command from the command line or from PowerShell:

>

To upgrade Chocolatey Font Helpers Extension, run the following command from the command line or from PowerShell:

>

To uninstall Chocolatey Font Helpers Extension, run the following command from the command line or from PowerShell:

>

Deployment Method:

NOTE

This applies to both open source and commercial editions of Chocolatey.

1. Enter Your Internal Repository Url

(this should look similar to https://community.chocolatey.org/api/v2/)


2. Setup Your Environment

1. Ensure you are set for organizational deployment

Please see the organizational deployment guide

2. Get the package into your environment

  • Open Source or Commercial:
    • Proxy Repository - Create a proxy nuget repository on Nexus, Artifactory Pro, or a proxy Chocolatey repository on ProGet. Point your upstream to https://community.chocolatey.org/api/v2/. Packages cache on first access automatically. Make sure your choco clients are using your proxy repository as a source and NOT the default community repository. See source command for more information.
    • You can also just download the package and push it to a repository Download

3. Copy Your Script

choco upgrade chocolatey-font-helpers.extension -y --source="'INTERNAL REPO URL'" [other options]

See options you can pass to upgrade.

See best practices for scripting.

Add this to a PowerShell script or use a Batch script with tools and in places where you are calling directly to Chocolatey. If you are integrating, keep in mind enhanced exit codes.

If you do use a PowerShell script, use the following to ensure bad exit codes are shown as failures:


choco upgrade chocolatey-font-helpers.extension -y --source="'INTERNAL REPO URL'" 
$exitCode = $LASTEXITCODE

Write-Verbose "Exit code was $exitCode"
$validExitCodes = @(0, 1605, 1614, 1641, 3010)
if ($validExitCodes -contains $exitCode) {
  Exit 0
}

Exit $exitCode

- name: Install chocolatey-font-helpers.extension
  win_chocolatey:
    name: chocolatey-font-helpers.extension
    version: '0.0.4'
    source: INTERNAL REPO URL
    state: present

See docs at https://docs.ansible.com/ansible/latest/modules/win_chocolatey_module.html.


chocolatey_package 'chocolatey-font-helpers.extension' do
  action    :install
  source   'INTERNAL REPO URL'
  version  '0.0.4'
end

See docs at https://docs.chef.io/resource_chocolatey_package.html.


cChocoPackageInstaller chocolatey-font-helpers.extension
{
    Name     = "chocolatey-font-helpers.extension"
    Version  = "0.0.4"
    Source   = "INTERNAL REPO URL"
}

Requires cChoco DSC Resource. See docs at https://github.com/chocolatey/cChoco.


package { 'chocolatey-font-helpers.extension':
  ensure   => '0.0.4',
  provider => 'chocolatey',
  source   => 'INTERNAL REPO URL',
}

Requires Puppet Chocolatey Provider module. See docs at https://forge.puppet.com/puppetlabs/chocolatey.


4. If applicable - Chocolatey configuration/installation

See infrastructure management matrix for Chocolatey configuration elements and examples.

Package Approved

This package was approved as a trusted package on 23 Nov 2024.

Description

The chocolatey-font-helpers.extension provides helper functions to assist Chocolatey packages easily install and uninstall "loose" (i.e. without an installer) FNT, FON, OTF, TTC, and TTF fonts system-wide.

This extension is based on a MS Blog post and became all-but necessary when newer versions of Windows started redirecting the often-used AddFontFile() method into the user's profile rather than the C:\Windows\Fonts directory as it had for many previous years.

These functions may be used in your Chocolatey package install/uninstall scripts by declaring this package a dependency in your package's nuspec.

USAGE:

  • Single Font: Will return a "0" for success and a "1" for failure.

    Install-ChocolateyFont "FilePath\FontName.ext"
    Uninstall-ChocolateyFont "FontName.ext"

  • Multiple Fonts: Will return the number of successful installs/uninstalls

    Install-ChocolateyFont $ListOfFontPathsOrFolder -multiple
    Uninstall-ChocolateyFont $ListOfFontFileNames -multiple

  • (New!) Wildcards: Install now accepts a wildcard (must use -multiple)

    Install-ChocolateyFont "FilePath\BaseFontName*.ext" -multiple

  • (New!) Uninstall-ChocolateyFont should now work with zero parameters. Install should create a log file ("FontFilesInstalled.log") in the $env:ChocolateyPackageFolder. Uninstall will use that (if present) to identify the fonts to remove. Your entire ChocolateyUninstall.ps1 could be a simple as: Remove-Font

Let the easy-peasy font packages flow!


Click here to Patreon-ize the package maintainer.



extensions\FontHelp.psm1
$scriptRoot = Split-Path -Path $MyInvocation.MyCommand.Definition

$publicFunctions = @(
   'Install-ChocolateyFont',
   'Uninstall-ChocolateyFont'
)

$publicAliases = @(
   'Add-Font',
   'Remove-Font'
)

Get-ChildItem -Path "$scriptRoot\*.ps1" | ForEach-Object { . $_ }
Export-ModuleMember -Function $publicFunctions -Alias $publicAliases
extensions\Install-ChocolateyFont.ps1
<#
.SYNOPSIS
   Installs a font or set of fonts.

.DESCRIPTION
   This function copies fonts to the system Fonts folder, adds the font registry
   keys and installs the font resources.  
  
   It only works with FNT, FON, OTF, TTC, TTF fonts.

   By default, it accepts only a single font file path, but the -multiple
   switch allows it to accept either a folder path or a list of font
   path names where it will attempt to install all of them.

.EXAMPLE
   Installs a single font
      PS C:\> Install-ChocolateyFont "FilePath\FontName.ext"

.EXAMPLE
   Installs all fonts in a folder
      PS C:\> Install-ChocolateyFont "FullFolderPath" -multi

.EXAMPLE
   Installs all fonts contained in a list of file paths
      PS C:\> Install-ChocolateyFont $ListOfFontFilePaths -multi

.INPUTS
   A string font or folder path or an array of strings of paths to font files.

.OUTPUTS
   Default:  "0" for success, "1" for failure
   With -multiple switch:  The number of fonts successfully installed.

.NOTES
   Aliased as Add-Font.
#>
function Install-ChocolateyFont { 
   param(
      [Parameter(Mandatory=$true)][string[]]$Paths,
      [Parameter(Mandatory=$false)][switch]$Multiple=$false
   )
   
   # Establish some basic starting points
   $SuccessList = @()
   $FontsFolder = (New-Object -ComObject Shell.Application).namespace(0x14).self.path
   $fontRegistryPath = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts'
   $FontFileTypes = @{
            '.fon' = ''
            '.fnt' = ''
            '.ttf' = ' (TrueType)'
            '.ttc' = ' (TrueType)'
            '.otf' = ' (OpenType)'
   }
   try { $LoadedType = [FontResource.AddRemoveFonts].ispublic } catch {$LoadedType = $false}
   if (-not $LoadedType) {
      New-FontResourceType
   }

   if (-not $Multiple) {
      If ($Paths.count -gt 1) {
         Throw "The '-multiple' switch must be used to install more than a single font."
      } elseif (Test-Path $Paths -PathType Container) {
         Throw "The '-multiple' switch must be used to install all fonts in a folder."
      } elseif ($Paths -match '\*') {
         Throw "The '-multiple' switch must be used to install more than a single font."
      }
      $FilePaths = $Paths
   } else {
      $FilePaths = @()
      Foreach ($Item in $Paths) {
         if (($Item -match '\*') -or (Test-Path $Item -PathType Container)) {
            $FilePaths += Get-ChildItem "$Item" -Include ('*.fon','*.otf','*.ttc','*.ttf') -Recurse | 
                              Select-Object -ExpandProperty FullName
         } else { $FilePaths += $Item }
      }
   }

   Write-Verbose "Files requested for installation:  $($FilePaths.count)"

   foreach ($Path in $FilePaths) {
      # Skip non-supported file types
      If (-not $FontFileTypes.ContainsKey(".$($path.split('.')[-1])")) { 
         Write-Warning "'$Path' is not a file of type $($FontFileTypes.keys -join ', ')."
         continue
      }
      # Skip non-existant files
      If (-not (Test-Path $Path)) {
         Write-Warning "File Path '$Path' does not exist!"
         continue
      }
   
      $File = Get-Item $Path
      $FolderObj = (New-Object -ComObject shell.application).namespace($File.directoryname)
      $FileObj = $FolderObj.Items().Item($File.Name)
      $FontName = $FolderObj.GetDetailsOf($FileObj,21)

      try {
         $ErrorActionPreference = 'Stop'
         Copy-Item $File.FullName -destination $FontsFolder -Force

         $fontFinalPath = Join-Path $FontsFolder $File.Name
         $retVal = [FontResource.AddRemoveFonts]::AddFont($fontFinalPath)

         if ($retVal -eq 0) {
            Throw "Font resource, '$($File.FullName)', installation failed"
         } else {
            Write-Verbose "Font resource, '$($File.FullName)', installed successfully"
            $SuccessList += $File.Name
            Set-ItemProperty -Path "$($fontRegistryPath)" -Name "$FontName$($FontFileTypes.item($File.Extension))" -Value "$($File.Name)" -Type STRING -Force
         }
      } catch {
         Write-Warning "An error occured installing '$($File.FullName)'"
         Write-Warning "Exception: $($_.Exception.Message)"
         if ($error -ne $null -and $error[0] -ne $null) {
            Write-Warning "$($error[0].ToString())"
            $error.clear()
         } else {
            Write-Warning "$($_.ToString())"
         }
      }
   }
   
   if ($SuccessList) {
      # Uninstalling will be much easier if the successfully 
      # installed font files are logged for later reference.
      $InstalledLogFile = Join-Path $env:ChocolateyPackageFolder 'FontFilesInstalled.log'
      $SuccessList | Out-File $InstalledLogFile -Force
   }

   If ($Multiple) {
      Return $SuccessList.count
   } elseif ($SuccessList.count) {
      Return 0
   } else {
      Return 1
   }
}

Set-Alias Add-Font Install-ChocolateyFont
extensions\New-FontResourceType.ps1
<#
.SYNOPSIS
   Defines a font resource type.

.DESCRIPTION
   This private function defines a font resource type from C# code 
   with methods to add a font resource and to remove a font resource.

.EXAMPLE
   PS C:\> New-FontResourceType
   PS C:\> [FontResource.AddRemoveFonts]::AddFont($localfontPath)

.INPUTS
   none

.OUTPUTS
   none
.NOTES
   The C# code borrows heavily from the code downloadable here:
   https://blogs.technet.microsoft.com/deploymentguys/2010/12/04/adding-and-removing-fonts-with-windows-powershell/
   It does not appear to work with UNC paths.
#>
Function New-FontResourceType {
   $fontCSharpCode = @'
   using System;
   using System.Collections.Generic;
   using System.Text;
   using System.IO;
   using System.Runtime.InteropServices;

   namespace FontResource {
       public class AddRemoveFonts {
           private static IntPtr HWND_BROADCAST = new IntPtr(0xffff);

           [DllImport("gdi32.dll")]
           static extern int AddFontResource(string lpFilename);

           [DllImport("gdi32.dll")]
           static extern int RemoveFontResource(string lpFileName);

           [return: MarshalAs(UnmanagedType.Bool)]
           [DllImport("user32.dll", SetLastError = true)]
           private static extern bool PostMessage(IntPtr hWnd, WM Msg, IntPtr wParam, IntPtr lParam);

           public enum WM : uint {
               FONTCHANGE = 0x001D
           }

           public static int AddFont(string fontFilePath) {
               FileInfo fontFile = new FileInfo(fontFilePath);
               if (!fontFile.Exists) { throw new FileNotFoundException("Font file not found"); }
               try {
                   int retVal = AddFontResource(fontFilePath);
                   bool posted = PostMessage(HWND_BROADCAST, WM.FONTCHANGE, IntPtr.Zero, IntPtr.Zero);
                   return retVal;
               }
               catch { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); }
           }

           public static int RemoveFont(string fontFileName) {
               try {
                   int retVal = RemoveFontResource(fontFileName);
                   bool posted = PostMessage(HWND_BROADCAST, WM.FONTCHANGE, IntPtr.Zero, IntPtr.Zero);
                   return retVal;
               }
               catch { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); }
           }
       }
   }
'@
   Add-Type $fontCSharpCode
}
extensions\Uninstall-ChocolateyFont.ps1
<#
.SYNOPSIS
   Uninstalls a font or set of fonts.

.DESCRIPTION
   This function deletes fonts from the system Fonts folder, removes the font 
   registry keys and removes the font resources.  
  
   It only works with FNT, FON, OTF, TTC, TTF fonts.

   By default, it accepts only a single font file, but the -multiple
   switch allows it to accept a list of font file names where it will 
   attempt to uninstall all of them.

.EXAMPLE
   Uninstalls a single font
      PS C:\> Uninstall-ChocolateyFont "FontName.ext"

.EXAMPLE
   Uninstalls all fonts contained in a list of file paths
      PS C:\> Uninstall-ChocolateyFont $ListOfFontFiles -multi

.INPUTS
   A string or array of strings of names of font files (including extensions)
   in the System Fonts folder.

.OUTPUTS
   Default:  "0" for success, "1" for failure
   With -multiple switch:  The number of fonts successfully uninstalled.

.NOTES
   Aliased as Remove-Font.
#>
function Uninstall-ChocolateyFont { 
   param(
      [Parameter(Mandatory=$false)][string[]]$FontFiles,
      [Parameter(Mandatory=$false)][switch]$Multiple=$false
   )
   
   # Establish some basic starting points
   $successes = 0
   $FontsFolder = (New-Object -ComObject Shell.Application).namespace(0x14).self.path
   $fontRegistryPath = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts'
   $FontFileTypes = @('.fon','.fnt','.ttf','.ttc','.otf')

   try { $LoadedType = [FontResource.AddRemoveFonts].ispublic } catch {$LoadedType = $false}
   if (-not $LoadedType) {
      New-FontResourceType
   }

   if (-not $FontFiles) {
      $InstalledLogFile = Join-Path $env:ChocolateyPackageFolder 'FontFilesInstalled.log'
      if (-not (Test-Path $InstalledLogFile)) {
         $Msg = "Font file names were not provided and the 'FontFilesInstalled.log' file was not found! `n" +
                  'No fonts can be removed if they are not identified.'
         Throw $Msg
      } else {
         $FontFiles = Get-Content $InstalledLogFile
         if ($FontFiles.count -gt 1) {
            $Multiple = $true
         }
      }
   }

   if ((-not $Multiple) -and ($FontFiles.count -gt 1)) {
      Throw "The '-multiple' switch must be used to uninstall more than a single font."
   }

   # Get installed font names and filenames
   $FontKeyProperties = (Get-ItemProperty $fontRegistryPath).PsObject.Properties | 
                           Where-Object {$_.value -match "(\$($fontfiletypes -join '|\'))`$"}

   foreach ($Item in $FontFiles) {
      # Skip non-supported file types
      If (-not $FontFileTypes -contains ".$($Item.split('.')[-1])") { 
         Write-Warning "'$Item' is not a file of type $($FontFileTypes -join ', ')."
         continue
      }
      # Skip non-existant files
      $FontPath = Join-Path $FontsFolder $Item
      If (-not (Test-Path $FontPath)) {
         Write-Warning "File Path '$FontPath' does not exist!"
         continue
      }
      $File = Get-Item $FontPath

      foreach($property in $FontKeyProperties) {
         if($Item -eq $property.Value) {
            $FontName = $property.Name
            break
         }
      }

      try {
         $ErrorActionPreference = 'Stop'
         $retVal = [FontResource.AddRemoveFonts]::RemoveFont($FontPath)
         if ($retVal -eq 0) {
            Throw "Font resource, '$FontPath', removal failed"
         } else {
            Write-Verbose "Font resource, '$($File.FullName)', removed successfully"
            Remove-ItemProperty -Path $fontRegistryPath -Name "$FontName" -Force
            Remove-Item $FontPath -Force
            $successes++
         }
      }
      catch
      {
         Write-Warning "An error occured removing '$Item'."
         Write-Warning "Exception: $($_.Exception.Message)"
         if ($error -ne $null -and $error[0] -ne $null) {
            Write-Warning "$($error[0].ToString())"
            $error.clear()
         } else {
            Write-Warning "$($_.ToString())"
         }
      }
   }
   
   If ($Multiple) {
      Return $successes
   } elseif ($successes) {
      Return 0
   } else {
      Return 1
   }
}

Set-Alias Remove-Font Uninstall-ChocolateyFont

Log in or click on link to see number of positives.

In cases where actual malware is found, the packages are subject to removal. Software sometimes has false positives. Moderators do not necessarily validate the safety of the underlying software, only that a package retrieves software from the official distribution point and/or validate embedded software against official distribution point (where distribution rights allow redistribution).

Chocolatey Pro provides runtime protection from possible malware.

Add to Builder Version Downloads Last Updated Status
Chocolatey Font Helpers Extension 0.0.3.1 37683 Sunday, November 1, 2020 Approved
Chocolatey Font Helpers Extension 0.0.3 291 Saturday, October 31, 2020 Approved
Chocolatey Font Helpers Extension 0.0.2 24842 Wednesday, September 11, 2019 Approved
Chocolatey Font Helpers Extension 0.0.2-pre 202 Monday, September 9, 2019 Exempted
Chocolatey Font Helpers Extension 0.0.1 1143 Tuesday, July 24, 2018 Approved

CHANGE LOG:

  • 0.0.1 - initial release
  • 0.0.2 - Cleaned up and added multiple option
  • 0.0.3 - Better exception handling, tests for already loaded type
  • 0.0.3.1 - Corrected ignorant attempt at C-sharp exception handling
  • 0.0.4 - Install accepts wildcards and logs installed font filenames. Uninstall can read log file to identify fonts to remove.

This package has no dependencies.

Discussion for the Chocolatey Font Helpers Extension Package

Ground Rules:

  • This discussion is only about Chocolatey Font Helpers Extension and the Chocolatey Font Helpers Extension package. If you have feedback for Chocolatey, please contact the Google Group.
  • This discussion will carry over multiple versions. If you have a comment about a particular version, please note that in your comments.
  • The maintainers of this Chocolatey Package will be notified about new comments that are posted to this Disqus thread, however, it is NOT a guarantee that you will get a response. If you do not hear back from the maintainers after posting a message below, please follow up by using the link on the left side of this page or follow this link to contact maintainers. If you still hear nothing back, please follow the package triage process.
  • Tell us what you love about the package or Chocolatey Font Helpers Extension, or tell us what needs improvement.
  • Share your experiences with the package, or extra configuration or gotchas that you've found.
  • If you use a url, the comment will be flagged for moderation until you've been whitelisted. Disqus moderated comments are approved on a weekly schedule if not sooner. It could take between 1-5 days for your comment to show up.
comments powered by Disqus