【问题标题】:Using a variable to define a hashtable name in Powershell在 Powershell 中使用变量定义哈希表名称
【发布时间】:2021-08-07 01:38:50
【问题描述】:

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

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 的几个变量喜欢阅读。

【问题讨论】:

  • New-Variable 创建了您要求的变量:$testName.Add(1,2)。动态命名变量的目的是什么?您想要实现的目标是 $hashTable = @{} 无法实现的?
  • 如果您想为每个文件创建一个哈希表,您可以使用“主”哈希表来存储所有这些 - 例如$allHashes = @{}; foreach( $filename in $filenames ) { $fileHashtable = @{ ... }; $allHashes.Add($filename, $fileHashTable) }。然后,您可以使用$allHashes[$FileName] 访问“文件哈希表”或遍历键以处理每个“文件哈希表”。
  • @MathiasR.Jessen - 你说得对,$hashTable = @{} 在生成空哈希表时效果相当好(并且也很简洁)。失败在于填充由此生成的哈希表。我应该在我的问题中更明确。
  • 好的,那么当您尝试填充它时会发生什么$hashTable.Add('key', 'value')$hashTable['key'] = 'value' 会抛出错误吗?
  • @MathiasR.Jessen - 如原始问题所述, $hashTable.Add('key','value') 抛出错误 [System.Management.Automation.PSVariable] 不包含方法命名为“添加”。

标签: powershell hashtable


【解决方案1】:

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

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

# 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 文件的内容,您可以使用名称和密钥作为索引

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

【讨论】:

  • 这不是我需要的。我需要能够引用具有文件内容定义的键和值的哈希表。如图所示,这只是创建了文件 name 的哈希表,而我需要将其解析为自己的哈希表。我认为@mclayton 正在酝酿解决方案。
  • @ProgrammerByForce 你能update your question 实际反映你的要求吗?文件内容是什么?
  • @ProgrammerByForce 谢谢,样本数据让你更清楚你想要做什么,我已经更新了答案
  • Mathias R. Jessen - 谢谢 - 我相信我可以完成这项工作。感谢您的帮助。
猜你喜欢
  • 2015-02-15
  • 2020-11-30
  • 2011-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-02
相关资源
最近更新 更多