Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell script to amend certain lines in a text file

Tags:

powershell

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.

like image 808
Alex Avatar asked Sep 21 '25 04:09

Alex


1 Answers

  • 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.

like image 64
mklement0 Avatar answered Sep 23 '25 06:09

mklement0