如何解决在 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。