我正在尝试运行这个脚本,它基本上从文本文件中读取/解释文本并将“键”和“值”存储到哈希表中。现在我想在从文本文件中读取文本时更改特定的键和值。
以下是我文件中的文本:
line1 = apple
line2 = firetruck
line3 = cricket
line4 = gorilla
line5 = elephant
line6 = banana
line7 = jumper
line8 = hat
line9 = deer
line10 = igloo
这是我的代码:
param
(
[Parameter(Mandatory=$true, HelpMessage="Please specify the text filename.")]$fileName
)
$hashTable = @{}
$textFile = Get-Content $filename | ForEach-Object `
{
$equalindex = $_.IndexOf("=")
$key = $_.Substring(0,$equalindex)
if($key -like "line2")
{
$key = "line2 has been changed"
}
$remainingLen = (($_.Length - 1) -$equalindex)
$value = $_.Substring($equalindex +1, $remainingLen)
if($value -like "value2")
{
$value = "value2 has been changed"
}
$hashtable.Add($key,$value)
}
$hashtable.Set_Item("line5","line5 value has been changed")
$hashtable.GetEnumerator() | Sort-Object name
当我运行我的代码时,它会输出哈希表,但不会更改我的“line2”键或“value2”值。这是做我想要完成的事情的正确/最合乎逻辑的方式吗?