我正在尝试运行这个脚本,它基本上从文本文件中读取/解释文本,并将“key”和“value”存储到哈希表中。现在我想在读取文本文件中的文本时更改特定的键和值。
以下是我文件中的文字:
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”值。这是我正在努力完成的正确/最合乎逻辑的方式吗?
答案 0 :(得分:3)
您需要删除前导和(或)尾随空格。试试这个:
$ht=@{}
Get-Content $filename | foreach{
$key,$value = $_.Split('=') | foreach {$_.Trim()}
if($key -like "line2")
{
$key = "line2 has been changed"
}
if($value -like "value2")
{
$value = "value2 has been changed"
}
$ht.Add($key,$value)
}
$ht.GetEnumerator() | Sort-Object name
Name Value
---- -----
line1 apple
line10 igloo
line2 has been changed firetruck
line3 cricket
line4 gorilla
line5 elephant
line6 banana
line7 jumper
line8 hat
line9 deer
答案 1 :(得分:1)
我认为尾随的空间会让你失望。
改变这个:
$key = $_.Substring(0,$equalindex)
到此:
$key = $_.Substring(0,$equalindex).Trim(' ')
或者索引可能已关闭,因为这似乎也有效:
$key = $_.Substring(0,$equalindex - 1)