I’m trying to run this script that basically reads/interprets text in from a textfile and stores the “key” and “value” into a hashtable. Now I want to change a specific key and value as I am reading the text from the text file.
The following is the text in my file:
line1 = apple
line2 = firetruck
line3 = cricket
line4 = gorilla
line5 = elephant
line6 = banana
line7 = jumper
line8 = hat
line9 = deer
line10 = igloo
Here is my code:
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
When I run my code it outputs the hashtable but does not change my “line2” key or my “value2” value. Is this the correct/most logical way to do what I’m trying to accomplish?
You need to remove leading and (or) trailing spaces. Try this: