在 Powershell 中使用变量定义哈希表名称

问题描述

我正在将一系列文本文件读入哈希表,以便我可以在脚本中引用它们。文本文件的格式很好,可以作为名称/值对。 文本文件格式为:

a b
c d
e f
g h

其中 'a,c,e,g' 是键,'b,d,f,h' 是值......除了超过 1000 行。

例如,我在我的文件名的一部分之后成功命名了一个空哈希表:

$FileName = 'testName' #example

$hashName = new-variable -Name $FileName -Value @{}

参考。堆栈溢出文章 Calling/Setting a variable with a variable in the name

我现在有一个名为 testName 的空哈希表。但是,我无法通过变量 $hashName 添加到 testName。

"$hashName".Add(1,2)

失败,因为 [System.String] 不包含名为“Add”的方法

$hashName.Add(1,2)

失败,因为 [System.Management.Automation.PSVariable] 不包含名为“Add”的方法。 (有道理)

请注意, $testName.Add(1,2) 工作得很好,但这对我没有好处,因为我想遍历从多个文件提取的 $testName 的几个变量喜欢阅读。

解决方法

这可能不是您想根据文件名命名的变量 - 您需要使用文件名作为哈希表中的入口键。 >

然后您可以在第一个中嵌套其他哈希表,例如每个文件一个:

# Create hashtable,assign to a variable named 'fileContents'
$fileContents = @{}

# Loop through all the text files with ForEach-Object
Get-ChildItem path\to\folder -File -Filter *.txt |ForEach-Object {
    # Now we can use the file name to create entries in the hashtable
    # Let's create a (nested) hashtable to contain the key-value pairs from the file
    $fileContents[$_.Name] = @{}

    Get-Content -LiteralPath $_.FullName |ForEach-Object {
        # split line into key-value pair
        $key,$value = -split $_

        # populate nested hashtable
        $fileContents[$_.Name][$key] = $value
    }
}

$fileContents 现在将包含一个哈希表,其中每个条目都有一个文件名作为其键,另一个哈希表包含来自相应文件的键值对作为其值。

例如,要访问名为 c 的密钥 data.txt 文件的内容,您可以使用名称和密钥作为索引

$fileName = 'data.txt'
$key = 'c'
$fileContents[$fileName][$key] # this will contain the string `d`,given your sample input