首页 > 解决方案 > 使用两个数组创建注册表键/值

问题描述

尝试为新 PC 自动化我们的字体安装过程。

为了安装字体,Windows 将 .ttf、.otf 等文件添加到 C:\Windows\Fonts,然后在 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts 中创建相应的注册表项。典型的注册表项如下所示:

宋体 (TrueType) | 宋体.ttf

为了自动执行此操作,我使用 Get-ChildItem 创建了两个数组:

$names = Get-ChildItem -Path "C:\corp\install\fonts" | Select-Object name | Out-String | ForEach-Object {$_ -Replace "----","" ` -Replace "Name","" ` -Replace ".otf","" ` -Replace ".ttf","" } | ForEach-Object { $_.Trim() }
$files = Get-ChildItem -Path "C:\corp\install\fonts" | Select-Object name | Out-String | ForEach-Object {$_ -Replace "----","" ` -Replace "Name","" } | ForEach-Object { $_.Trim() }

$names 中的每个 $name 将是注册表项的名称,$files 中的每个 $file 将是该注册表项的数据。

我该怎么做呢?我尝试使用哈希表、PSObjects、嵌套的 ForEach 循环,但都无济于事。我很难在这里和其他地方找到与这种情况完全匹配的任何东西。

错误检查并不是真正必要的,因为总会有一个相应的值。

修订后的最终解决方案:

Write-Host "Installing corporate fonts..."
Copy-Item -Path "C:\corp\install\fonts\*" -Destination "C:\Windows\Fonts" -Force -Recurse

$fontList = @()

$fonts = Get-ChildItem "C:\corp\install\fonts" | Select-Object -ExpandProperty Name

ForEach ( $font in $fonts ) {

    $fontList += [PSCustomObject] @{ 
        Name = $font -Replace ".otf","" ` -Replace ".ttf",""
        File = $font
    } |

    ForEach-Object {
        New-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts" -Name $_.Name -Value $_.File
    }
}

标签: arrayswindowspowershell

解决方案


我必须承认我不完全理解你的问题,所以如果这个回答离题太远了,请原谅我,但这就是你要找的吗?一张同时包含两条数据的表?

Function CreateVariables {

    $namevariables = @()

    $filenames = ( Get-ChildItem "C:\corp\install\fonts" ).name 

    Foreach ( $name in $filenames ){

        $namevariables += [PSCustomObject] @{ 
            Name = $name -Replace "----","" ` -Replace "Name","" ` -Replace ".otf","" ` -Replace ".ttf","" 
            File = $name -Replace "----","" ` -Replace "Name",""
        }
    }

    Return $namevariables
}

CreateVariables

推荐阅读