Downloads:

3,226

Downloads of v 0.0.2:

2,265

Last Update:

11 Sep 2019

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

0.0.2 | Updated: 11 Sep 2019

Downloads:

3,226

Downloads of v 0.0.2:

2,265

Software Author(s):

  • Teknowledgist and Bill Curran

Chocolatey Font Helpers Extension 0.0.2

All Checks are Passing

2 Passing Test


Validation Testing Passed


Verification Testing Passed

Details

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:

>

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

1. Ensure you are set for organizational deployment

Please see the organizational deployment guide

  • 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://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. Enter your internal repository url

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

4. Choose your deployment method:


choco upgrade chocolatey-font-helpers.extension -y --source="'STEP 3 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="'STEP 3 URL'" 
$exitCode = $LASTEXITCODE

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

Exit $exitCode

- name: Ensure chocolatey-font-helpers.extension installed
  win_chocolatey:
    name: chocolatey-font-helpers.extension
    state: present
    version: 0.0.2
    source: STEP 3 URL

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

Coming early 2020! Central Managment Reporting available now! More information...


chocolatey_package 'chocolatey-font-helpers.extension' do
  action    :install
  version  '0.0.2'
  source   'STEP 3 URL'
end

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


Chocolatey::Ensure-Package
(
    Name: chocolatey-font-helpers.extension,
    Version: 0.0.2,
    Source: STEP 3 URL
);

Requires Otter Chocolatey Extension. See docs at https://inedo.com/den/otter/chocolatey.


cChocoPackageInstaller chocolatey-font-helpers.extension
{
   Name     = 'chocolatey-font-helpers.extension'
   Ensure   = 'Present'
   Version  = '0.0.2'
   Source   = 'STEP 3 URL'
}

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


package { 'chocolatey-font-helpers.extension':
  provider => 'chocolatey',
  ensure   => '0.0.2',
  source   => 'STEP 3 URL',
}

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


salt '*' chocolatey.install chocolatey-font-helpers.extension version="0.0.2" source="STEP 3 URL"

See docs at https://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.chocolatey.html.

5. If applicable - Chocolatey configuration/installation

See infrastructure management matrix for Chocolatey configuration elements and examples.

This package was approved by moderator gep13 on 11 Sep 2019.

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"

  • (New!) Multiple Fonts Will return the number of successful installs/uninstalls

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

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
   $successes = 0
   $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)'
   }
   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."
      }
      $FilePaths = $Paths
   } elseif (Test-Path $Paths -PathType Container) {
      $FilePaths = Get-ChildItem $Paths -Include ('*.fon','*.otf','*.ttc','*.ttf') -Recurse | 
                     Select-Object -ExpandProperty FullName
   } else {
      $FilePaths = $Paths
   }

   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 {
         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"
            Set-ItemProperty -Path "$($fontRegistryPath)" -Name "$FontName$($FontFileTypes.item($File.Extension))" -Value "$($File.Name)" -Type STRING -Force
            $successes++
         }
      } catch {
         Write-Warning "An error occured installing '$($File.FullName)'"
         Write-Warning "$($error[0].ToString())"
         $error.clear()
      }
   }
   
   If ($Multiple) {
      Return $successes
   } elseif ($successes) {
      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) { return 0; }
               try {
                   int retVal = AddFontResource(fontFilePath);
                   bool posted = PostMessage(HWND_BROADCAST, WM.FONTCHANGE, IntPtr.Zero, IntPtr.Zero);
                   return retVal;
               }
               catch { return 0; }
           }

           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 { return 0; }
           }
       }
   }
'@
   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=$true)][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')

   New-FontResourceType

   if ((-not $Multiple) -and ($FontFiles.count -gt 1)) {
      Throw "The '-multiple' switch must be used to install 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 {
         $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 "$($error[0].ToString())"
         $error.clear()
      }
   }
   
   If ($Multiple) {
      Return $successes
   } elseif ($successes) {
      Return 0
   } else {
      Return 1
   }
}

Set-Alias Remove-Font Uninstall-ChocolateyFont

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.

Version Downloads Last Updated Status
Chocolatey Font Helpers Extension 0.0.2-pre 21 Monday, September 9, 2019 Exempted
Chocolatey Font Helpers Extension 0.0.1 930 Tuesday, July 24, 2018 Approved

###CHANGE LOG:

  • 0.0.1 - initial release
  • 0.0.2 - Cleaned up and added multiple option

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