PowerShell临时安装含非拉丁名称字体失败问题求助
解决PowerShell临时安装含非拉丁字符字体的问题
问题根源
- 非拉丁路径识别失败:原脚本的
DllImport默认使用CharSet.Ansi编码,无法正确解析含日文等非拉丁字符的字体文件路径,导致加载失败。 - 类型重复定义错误:重复运行脚本时,已定义的
AddFontResource.FontUtils类型未被覆盖,触发类型已存在的报错。
修正后的脚本
$dir = "fonts" $signature = @' [DllImport("gdi32.dll", CharSet = CharSet.Unicode)] public static extern int AddFontResource(string lpszFilename); '@ # 使用-Force参数强制覆盖已存在的类型定义 $type = Add-Type -MemberDefinition $signature ` -Name FontUtils -Namespace AddFontResource ` -Using System.Text -PassThru -Force foreach ($font in (Get-ChildItem -LiteralPath $dir -Recurse | Where-Object { $_.Extension -in ".ttf", ".otf" })) { $ffn = $font.FullName "loading($ffn)" >> file.txt # 显式传入完整的Unicode路径字符串 $loadResult = $type::AddFontResource($ffn) # 可选:输出加载结果,非0值表示成功加载的字体数量 Write-Host "加载字体:$ffn,结果代码:$loadResult" }
关键修正点
- 指定Unicode字符集:在
DllImport属性中添加CharSet = CharSet.Unicode,让系统自动调用Unicode版本的AddFontResourceW函数,支持非拉丁字符路径。 - 强制覆盖类型:添加
-Force参数到Add-Type命令,解决重复运行脚本时的类型已存在错误。 - 显式传入路径字符串:直接使用
$font.FullName而非FileInfo对象,避免隐式转换可能带来的编码问题。
替代方案:直接调用Unicode版本函数
也可以直接指定调用AddFontResourceW(专为Unicode路径设计的函数),无需设置CharSet:
$signature = @' [DllImport("gdi32.dll")] public static extern int AddFontResourceW(string lpszFilename); '@ # 后续调用改为: $loadResult = $type::AddFontResourceW($ffn)
内容的提问来源于stack exchange,提问作者user206904
相关产品推荐
相关产品推荐

