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

Using a variable to define a hashtable name in Powershell

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

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 现在将包含一个哈希表,其中每个条目都有一个文件名作为其键,另一个哈希表包含相应文件中的键值对作为其值。

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

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