0

I have a snippet of code which gets the content of each file and will replace values within it if it matches my variable list.

The code works fine. However, after the scan it's leaving a blank line at the end of the file which I do not want to happen.

# From the location set in the first statement
# Recurse through each file in each folder that has an extension defined
# in-Include
$configFiles = Get-ChildItem $Destination -Recurse -File -Exclude *.exe,*.css,*.scss,*.png,*.min.js

foreach ($file in $configFiles) {
    Write-Host $file.FullName

    # Get the content of each file and search and replace values as defined in
    # the searc/replace table 
    $fileContent = Get-Content $file.FullName
    $fileContent | ForEach-Object { 
        $line = $_

        $lookupTable.GetEnumerator() | ForEach-Object {
            # [Regex]::Escape($_.Key) treats regex metacharacters in the search
            # string as string literals
            if ($line -match [Regex]::Escape($_.Key)) {
                $line = $line -replace [Regex]::Escape($_.Key), $_.Value
            }
        }
        $line
    } | Set-Content $file.FullName
}

I've tried adding:

Set-Content $file.FullName -NoNewline

This just puts everything in the file on one line.

Some files will already have a blank line at the end which I want to stay the same, so I can't just remove the last line of every file.

How do I stop this script from adding a new line once finished scanning? $lookuptable for reference:

$lookupTable = @{
    'Dummy'  = $ReplacementValue
    'Dummy2' = $ReplacementValue    
}
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Cory
  • 161
  • 2
  • 13
  • What does $lookupTable look like? – Jacob Colvin May 16 '18 at 15:23
  • Could it be that a replcement takes place on the last line? BTW IMO the `if ($line -match ...` is superfluous, if it doesn't match nothing is replaced, if it matches it *is* replaced so the RegEx is evaluated twice for matches - so simply replace without the if. –  May 16 '18 at 15:32
  • No replacement does not happen on the last line, even if no matches are found in the file and nothing is replaced it still leaves a new line at the end. Thanks, I missed that I'll change that for the future :) – Cory May 16 '18 at 15:38

0 Answers0