I've got this script, which is supposed to open the ini file and change the line that starts with "ProjectPath=". It opens the file fine, reads the data, goes through each line, modifies the needed line in $line, but the $lines stays the same, so the output file gets written, but with unchanged data. What am I missing? Any help would be much appreciated as I've already spent hours on it.
# Get the file content as an array of lines
$lines = Get-Content "C:\TEMP\test.ini"
# Loop through the lines
foreach ($line in $lines) {
if ($line.StartsWith("ProjectPath=")) {
# Replace the line with the new value
$line = "ProjectPath=%USERPROFILE%\Documents"
}
}
# Write the modified lines back to the file
Set-Content "C:\TEMP\test.ini" $lines -Force
Nothing that I tried has helped.
As a general rule, assigning to the self-chosen iterator variable in a foreach
statement ($line = ...
, in your case) has no effect on the collection being enumerated - doing so simply updates the iterator variable in that iteration (and if you do not otherwise use this updated variable, the assignment is a no-op).
Instead of attempting in-place updating, you can use the pipeline to output the - conditionally modified - lines, using the ForEach-Object
cmdlet, which allows you to directly pipe them to Set-Content
:
(Get-Content 'C:\TEMP\test.ini') | # Note the required (...) enclosure
ForEach-Object {
if ($_.StartsWith('ProjectPath=')) {
'ProjectPath=%USERPROFILE%\Documents' # Replace the original line with this.
} else {
$_ # Pass the original line through.
}
} |
Set-Content 'C:\TEMP\test.ini' -Force
Note:
In the script block passed to ForEach-Object
, the automatic $_
variable refers to the input object (line, in this case) at hand.
Note how the Get-Content
call is enclosed in (...)
, the grouping operator, which ensures that the lines of the input file are read in full, up front, which is what allows writing back to that file as part of the same pipeline.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With