欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

BAT批处理、VBScript批量安装字体脚本分享

程序员文章站 2022-03-21 16:38:07
根据新系统要求,经常要部署一些原来系统里没有的字体,原先我为了图省事经常会要求用户手动安装字体文件,虽然windows的易用性做得相当不错,但是仍然要照顾一些不会安装字体的...

根据新系统要求,经常要部署一些原来系统里没有的字体,原先我为了图省事经常会要求用户手动安装字体文件,虽然windows的易用性做得相当不错,但是仍然要照顾一些不会安装字体的人,其实把这些字体打包进安装包更为方便,不过我觉得总不能每有新字体都要搞个安装包那么麻烦吧。更重要的是仍然有人会问我字体怎么安装,以前清一色的windows xp系统,我倒也方便,直接告知打开控制面板找到字体文件夹,把要安装的字体拖进去即可;现在有windows 7还是windows 8等各种版本windows系统,对于安装字体这个小小操作我也开始分情况讨论了。

使用特殊文件夹或者desktop.ini方法

使用特殊文件夹方法

windows保留了一种特殊文件夹引用,比如在windows xp的情况下,新建一个文件夹,然后在文件夹重命名后缀.{645ff040-5081-101b-9f08-00aa002f954e}(注意以点号分隔),然后这个文件夹就变成了回收站的一个引用,当我们点击进去的时候实际上进去的是回收站。

好了我在想对于字体是不是也可以搞个文件夹引用,这样直接叫用户把要安装的字体拖进去即可,大家注意到这个成功的关键在于后面那段长长的id号,那个学名叫做guid,通常可以通过注册表查询,主要路径在于:

复制代码 代码如下:
hkey_local_machine\software\microsoft\windows\currentversion\explorer

比如回收站就位于下面的注册表路径:
复制代码 代码如下:

hkey_local_machine\software\microsoft\windows\currentversion\explorer\desktop\namespace

对于字体我也在如下路径找到了:
复制代码 代码如下:

hkey_local_machine\software\microsoft\windows\currentversion\explorer\controlpanel\namespace

字体的guid是{d20ea4e1-3957-11d2-a40b-0c5020524152},但是当我新建一个文件夹并且名称以.{d20ea4e1-3957-11d2-a40b-0c5020524152}(注意点号)结尾,当我点进去时却不能进入字体文件夹,于是这个想法被验证为失败。

使用desktop.ini方法

其实建立特殊文件夹还有一个方法就是采用文件夹的desktop.ini,抱着试试的心态,我在文件夹内部建立了desktop.ini,内容如下:

复制代码 代码如下:

[.shellclassinfo]
iconfile=%systemroot%\system32\shell32.dll
iconindex=38
clsid={d20ea4e1-3957-11d2-a40b-0c5020524152}

很遗憾,依然不能直达字体目录,所以这一种办法也是行不通的。

本着方便群众的想法,我决定做个小小的程序,当然我首先求助了万能的google。原本想搞个桌面程序来着,也找到老外现成的代码fontreg – windows font registration & installation utility。后来随着研究的深入,突然发现这玩意儿用批处理或者脚本实现更为简单。

cmd或bat批处理安装字体

通常情况下字体文件夹位于c:\windows\fonts,转换为带环境变量的通用版本为%systemroot%\fonts\,我们也许想当然的认为将字体复制到这个路径下就完成了安装,其实不然,系统安装字体不单单是将字体文件复制到这个路径下,其还进行了其他操作,比如更新注册表字体列表。通常情况下这个列表位于路径如下:

复制代码 代码如下:

hkey_local_machine\software\microsoft\windows nt\currentversion\fonts

于是对于批处理来说,网上安装字体流程大概分为两派,首先第一步复制到fonts文件夹,这个是公认的,第二步则有不同:一派认为应该更新注册表;另一派则倾向于使用addfontresource这个函数。

使用addfontresource更新系统字体列表

什么是addfontresource函数?这是个win32 api函数,位于gdi32.dll动态链接库上,msdn参考见这里。我们可以编译调用这个函数,什么?“编译”?貌似和这里讲的批处理差远了吧,别急,好在这个函数签名不复杂,其有个addfontresourcea的ansi版本,这样给我们直接外部通过rundll32调用提供了可能,例如下面的代码片段:

复制代码 代码如下:

rundll32.exe gdi32.dll,addfontresourcea %systemroot%\fonts\字体.ttf

具体的代码如下(来源不详,将该批处理和ttf字体位于同一路径下,然后双击即可):

复制代码 代码如下:

for /f %%a in ('dir /x /b *.ttf') do (
dir %windir%fonts%%a>nul 2>nul||(copy %%a %windir%fonts>nul 2>nul&rundll32.exe gdi32.dll,addfontresourcea %windir%fonts%%a)
)

实际操作来看,这段代码在我的电脑上没有产生任何效果。

使用注册表更新系统字体列表

参考《windows 7: installing fonts via command line/script》这个帖子,找到下面的代码:

@echo off
title adding fonts..
rem filename: add_fonts.cmd
rem script to add truetype and opentype fonts for windows
rem by islam adel
rem 2012-01-16
 
rem how to use:
rem place the batch file inside the folder of the font files or:
rem optional add source folder as parameter with ending backslash and dont use quotes, spaces are allowed
rem example "add_fonts.cmd" c:\folder 1\folder 2\
 
if not "%*"=="" set src=%*
echo.
echo adding fonts..
echo.
for /f %%i in ('dir /b "%src%*.*tf"') do call :font %%i
rem optional reboot
rem shutdown -r -f -t 10 -c "reboot required for fonts installation"
echo.
echo done!
pause
exit
 
:font
echo.
rem echo file=%~f1
set ffile=%~n1%~x1
set fname=%~n1
set fname=%fname:-= %
if "%~x1"==".otf" set ftype=(opentype)
if "%~x1"==".ttf" set ftype=(truetype)
 
echo file=%ffile%
echo name=%fname%
echo type=%ftype%
 
copy /y "%src%%~n1%~x1" "%systemroot%\fonts\"
reg add "hklm\software\microsoft\windows nt\currentversion\fonts" /v "%fname% %ftype%" /t reg_sz /d "%ffile%" /f
goto :eof

仔细阅读代码后发现,这段批处理在复制字体并更新注册表后居然要重启电脑(汗~),这种做法显然对最终用户不太友好,综合以上我决定放弃批处理的方式安装字体。

使用vbscript安装字体

最后我还是干回老本行,使用vbscript脚本来实现这个功能。脚本的重点是采用shell.applicationactivex/com对象实现复制到系统特殊文件夹下,实际上这个操作和用户手动复制到字体文件夹下一样,系统会自动为我们安装字体而不需要我们顾及注册表更新的问题,对于vista及更高版本的系统来说,我参考了《the true ultimate font install for windows 7 and xp vbs》的做法,使用.invokeverb("install")直接调用字体文件对象的安装命令。

详细的代码如下(请复制的朋友手下留情,保留版权信息,谢谢):

复制代码 代码如下:

'
' file description : vbscript windows fonts installer
'
' copyright (c) 2012-2013 wangye. all rights reserved.
'
' author: wangye
' this code is distributed under the bsd license
'
' usage:
'    drag font files or folder to this script
'    or double click this script file, it will install fonts on the current directory
'    or select font directory to install
' *** 请不要移除此版权信息 ***
'
option explicit
 
const fonts = &h14&
const hkey_local_machine = &h80000002
const strcomputer = "."
 
const shell_my_computer = &h11
const shell_window_handle = 0
const shell_options = 0
function getopendirectory(title)
    dim shlapp,shlfdr,shlfdritem
 
    set shlapp = wsh.createobject("shell.application")
    set shlfdr = shlapp.namespace(shell_my_computer)
    set shlfdritem = shlfdr.self
    getopendirectory = shlfdritem.path
    set shlfdritem = nothing
    set shlfdr = nothing
 
    set shlfdr = shlapp.browseforfolder _
                (shell_window_handle, _
                title, _
                shell_options, _
                getopendirectory)
    if shlfdr is nothing then
        getopendirectory = ""
    else
        set shlfdritem = shlfdr.self
        getopendirectory = shlfdritem.path
        set shlfdritem = nothing
    end if
    set shlapp = nothing
end function
 
 
function isvista()
    isvista = false
    dim objwmiservice, coloperationsystems, objoperationsystem
    set objwmiservice = getobject("winmgmts:{impersonationlevel=impersonate}!\\" & strcomputer & "\root\cimv2")
    set coloperationsystems = objwmiservice.execquery ("select * from win32_operatingsystem")
        for each objoperationsystem in coloperationsystems
            if cint(left(objoperationsystem.version, 1)) > 5 then
                isvista = true
                exit function
            end if
        next
    set coloperationsystems = nothing
    set objwmiservice = nothing
end function
 
class fontinstaller
 
    private objshell
    private objfolder
    private objregistry
    private strkeypath
    private objregexp
    private objfilesystemobject
    private objdictfontfiles
    private objdictfontnames
    private pfncallback
    private blnisvista
 
    public property get filesystemobject
        set filesystemobject = objfilesystemobject
    end property
 
    public property let callback(value)
        pfncallback = value
    end property
 
    private sub class_initialize()
        strkeypath = "software\microsoft\windows nt\currentversion\fonts"
 
        set objshell = createobject("shell.application")
        set objfilesystemobject = createobject("scripting.filesystemobject")
        set objfolder = objshell.namespace(fonts)
        set objdictfontfiles = createobject("scripting.dictionary")
        set objdictfontnames = createobject("scripting.dictionary")
        set objregistry = getobject("winmgmts:{impersonationlevel=impersonate}!\\" &_
                     strcomputer & "\root\default:stdregprov")
        set objregexp = new regexp
            objregexp.global = false
            objregexp.pattern = "^([^\(]+) \(.+$"
 
        blnisvista = isvista()
        makefontnamelist
        makefontfilelist
    end sub
 
    private sub class_terminate()
        set objregexp = nothing
        set objregistry = nothing
        set objfolder = nothing
            objdictfontfiles.removeall
        set objdictfontfiles = nothing
            objdictfontnames.removeall
        set objdictfontnames = nothing
        set objfilesystemobject = nothing
        set objshell = nothing
    end sub
 
    private function getfilenamewithoutextension(byval filename)
        ' http://social.technet.microsoft.com/forums/en-us/ebe19301-541a-412b-8e89-08c4263cc60b/get-filename-without-extension
        dim result, i
        result = filename
        i = instrrev(filename, ".")
        if ( i > 0 ) then
        result = mid(filename, 1, i - 1)
        end if
        getfilenamewithoutextension = result
    end function
 
    private sub makefontnamelist()
        on error resume next
        dim strvalue,arrentrynames
        objregistry.enumvalues hkey_local_machine, strkeypath, arrentrynames
        for each strvalue in arrentrynames
           objdictfontnames.add objregexp.replace(strvalue, "$1"), strvalue
        next
        if err.number<>0 then err.clear
    end sub
 
    private sub makefontfilelist()
        on error resume next
        dim objfolderitem,colitems,objitem
        set objfolderitem = objfolder.self
        'wscript.echo objfolderitem.path
        set colitems = objfolder.items
        for each objitem in colitems
            objdictfontfiles.add getfilenamewithoutextension(objitem.name),objitem.name
        next
        set colitems = nothing
        set objfolderitem = nothing
        if err.number<>0 then err.clear
    end sub
 
    function getbasename(byval strfilename)
        getbasename = objfilesystemobject.getbasename(strfilename)
    end function
 
    public function pathaddbackslash(strfilename)
        pathaddbackslash = strfilename
        if objfilesystemobject.folderexists(strfilename) then
          dim last
          ' 文件夹存在
          ' 截取最后一个字符
          last = right(strfilename, 1)
          if last<>"\" and last<>"/" then
            pathaddbackslash = strfilename & "\"
          end if
        end if
    end function
 
    public function isfontinstalled(byval strname)
        isfontinstalled = objdictfontnames.exists(strname) or objdictfontfiles.exists(strname)
    end function
 
    public function isfontfileinstalled(byval strfilename)
        isfontfileinstalled = isfontinstalled(objfilesystemobject.getbasename(strfilename))
    end function
 
    public sub installfromfile(byval strfilename)
        dim strextension, strbasefilename, objcallback, nresult
        strbasefilename = objfilesystemobject.getbasename(strfilename)
        strextension = ucase(objfilesystemobject.getextensionname(strfilename))
 
        if len(pfncallback) > 0 then
            set objcallback = getref(pfncallback)
        else
            set objcallback = nothing
        end if
 
        if strextension = "ttf" or strextension = "ttc" or strextension = "otf" then
            if not isfontinstalled(strbasefilename) then
                if blnisvista then
                    dim objfont, objfontnamespace
                    set objfontnamespace = objshell.namespace(objfilesystemobject.getparentfoldername(strfilename))
                    set objfont = objfontnamespace.parsename(objfilesystemobject.getfilename(strfilename))
                        'wsh.echo objfilesystemobject.getparentfoldername(strfilename)
                        objfont.invokeverb("install")
                    set objfont = nothing
                    set objfontnamespace = nothing
                else
                'wsh.echo strfilename
                objfolder.copyhere strfilename
                end if
 
                nresult = 0
            else
                nresult = 1
            end if
        else
            nresult = -1
        end if
 
        if isobject(objcallback) then
            objcallback me, strfilename, nresult
            set objcallback = nothing
 
        end if
    end sub
 
    public sub installfromdirectory(byval strdirname)
        dim objfolder, colfiles, objfile
        set objfolder = objfilesystemobject.getfolder(strdirname)
        set colfiles = objfolder.files
        for each objfile in colfiles
            if objfile.size > 0 then
                installfromfile pathaddbackslash(strdirname) & objfile.name
            end if
        next
 
        set colfiles = nothing
        set objfolder = nothing
    end sub
 
    public sub setdragdrop(objargs)
        '
        dim i
        for i = 0 to objargs.count - 1
           if objfilesystemobject.fileexists(objargs(i)) then
                installfromfile objargs(i)
           elseif objfilesystemobject.folderexists(objargs(i)) then
                installfromdirectory objargs(i)
           end if
        next
    end sub
end class
 
sub forcecscriptexecution()
    '
    ' http://www.winhelponline.com/articles/185/1/vbscripts-and-uac-elevation.html
    dim arg, str
    if not lcase( right( wscript.fullname, 12 ) ) = "\cscript.exe" then
        for each arg in wscript.arguments
            if instr( arg, " " ) then arg = """" & arg & """"
            str = str & " " & arg
        next
 
        if isvista() then
            createobject( "shell.application" ).shellexecute _
                "cscript.exe","//nologo """ & _
                wscript.scriptfullname & _
                """ " & str, "", "runas", 1
        else
 
            createobject( "wscript.shell" ).run _
            "cscript //nologo """ & _
            wscript.scriptfullname & _
            """ " & str
 
        end if
        wscript.quit
    end if
end sub
 
sub displaymessage(byref objinstaller, byval strfilename, byval nresult)
    wscript.stdout.write "install " & objinstaller.getbasename(strfilename) & " ->>> "
    select case nresult
        case 0
            wscript.stdout.write "succeeded"
        case 1
            wscript.stdout.write "already installed"
        case -1
            wscript.stdout.write "failed (reason: not a font file)"
    end select
    wscript.stdout.write vbcrlf
end sub
 
sub pause(strpause)
     wscript.echo (strpause)
     wscript.stdin.read(1)
end sub
 
function vbmain(colarguments)
    vbmain = 0
 
    forcecscriptexecution()
 
    wsh.echo "easy font installer 1.0" & vbcrlf &_
              "written by wangye " & vbcrlf & vbcrlf
    dim objinstaller, objfso, objdictfontfiles
    set objinstaller = new fontinstaller
        objinstaller.callback = "displaymessage"
        if colarguments.count > 0 then
            objinstaller.setdragdrop colarguments
        else
            set objfso = objinstaller.filesystemobject
            set objdictfontfiles = createobject("scripting.dictionary")
            dim objfolder, colfiles, objfile, strdirname, strextension
            strdirname = objfso.getparentfoldername(wscript.scriptfullname)
            set objfolder = objfso.getfolder(strdirname)
            set colfiles = objfolder.files
            for each objfile in colfiles
                if objfile.size > 0 then
                    strextension = ucase(objfso.getextensionname(objfile.name))
                    if strextension = "ttf" or strextension = "ttc" or strextension = "otf" then
                        objdictfontfiles.add objfile.name, objinstaller.pathaddbackslash(strdirname) & objfile.name
                    end if
                end if
            next
 
            set colfiles = nothing
            set objfolder = nothing
            set objfso = nothing
 
            if objdictfontfiles.count > 0 then
                if msgbox("current directory has " & objdictfontfiles.count & " font files." & vbcrlf &_
                        vbcrlf & "click ok to continue install or cancel to select directory", 1) = 1 then
                      dim i, objitems
                      for i = 0 to  objdictfontfiles.count-1
                        objitems = objdictfontfiles.items
                        objinstaller.installfromfile objitems(i)
                      next
                else
                    strdirname = getopendirectory("select fonts directory:")
                    if strdirname<>"" then
                        objinstaller.installfromdirectory strdirname
                    else
                        wscript.echo "----- drag font file to this script -----"
                    end if
                end if
            end if
                objdictfontfiles.removeall
            set objdictfontfiles = nothing
        end if
    set objinstaller = nothing
 
    pause vbcrlf & vbcrlf & "press enter to continue"
end function
 
wscript.quit(vbmain(wscript.arguments))

这个脚本的使用方法很简单,将上述代码保存为vbs文件,然后将要安装的字体或者包含字体的文件夹拖放到这个脚本文件即可,还有个方法就是直接双击脚本,然后按照提示会自动安装与脚本同路径的字体文件或者提示选择字体所在路径以便于安装。

还有一处值得注意的是:我对已经安装的字体是采取建立字体列表,然后判断当前安装的字体是否存在于字体列表,字体列表的来源是已经安装的字体在系统的注册名(存在于注册表中)和已经安装的字体文件名。唯一遗憾的是我是通过比判断安装字体的文件名是否在字体列表中来判断字体是否安装,这里的问题主要是待安装的字体文件名不一定与字体真实的名字一致,字体真实的名字是需要读取二进制字体文件从中来获取的,这样脚本又复杂了,所以放弃了这种方式。