我正在尝试编写一个 Poweshell 脚本,用于安装给定目录中的所有字体(格式为
.ttf
和 .otf
)。但是我想忽略已经安装的字体。为此,我需要获取字体的名称(不是文件名)。
我该怎么做?
根据@LotPings 的评论进行编辑
您可以使用 .NET 来实现这一点。在下面的示例中,您将浏览给定路径中的文件列表,然后使用 PrivateFontCollection 类来检索字体名称。
Add-Type -AssemblyName System.Drawing
$path = "<path to the fonts>\*.ttf"
$ttfFiles = Get-ChildItem $path
$fontCollection = new-object System.Drawing.Text.PrivateFontCollection
$ttfFiles | ForEach-Object {
$fontCollection.AddFontFile($_.fullname)
$fontCollection.Families[-1].Name
}
基于 Micky Balladelli 提供的代码,以下代码添加了用字体名称重命名“.ttf”文件的功能:
Add-Type -AssemblyName System.Drawing
$path = ".\*.ttf"
$ttfFiles = Get-ChildItem $path
$fontCollection = new-object System.Drawing.Text.PrivateFontCollection
$ttfFiles | ForEach-Object {
# Add the font file to the collection to extract its name
$fontCollection.AddFontFile($_.FullName)
$fontName = $fontCollection.Families[-1].Name
# Generate a valid file name from the font name
$safeFontName = $fontName -replace "[^a-zA-Z0-9 -]", ""
$newFileName = "$safeFontName.ttf"
# Full path for the new file
$newFilePath = Join-Path -Path $_.Directory.FullName -ChildPath $newFileName
# Rename the file, checking if the new file name already exists
if (-not (Test-Path $newFilePath)) {
Rename-Item -Path $_.FullName -NewName $newFileName
Write-Host "Renamed $($_.Name) to $newFileName"
} else {
Write-Warning "A file named $newFileName already exists. Skipping $_."
}
}
# Dispose the font collection after processing
$fontCollection.Dispose()
只需将上述代码复制粘贴到PowerShell中即可运行。代码似乎有一个问题,有时它声称已经存在同名的文件,但实际上并不存在。当发生这种情况时,您只需多次运行整个代码即可。