Adding Lines to the Beginning and Ending of Files Using PowerShell

In dealing with an application with which I had little familiarity, I discovered that troubleshooting an app (in this case developed using ColdFusion) where many of the source code files are “included” dynamically can be difficult – especially when JavaScript scripts are combined that have functions with identical names.

Because so many of the functions were not only identically named, but also similarly constructed, I decided to add commented identifiers to the beginning and ending of each JS file.

This could be done in a number of ways, but given my recent forays into using PowerShell scripts, I chose that route again.

Stack Overflow PowerShell question
Stack Overflow and Google – developers’ best friends.

After some Googling and a brief visit to Stack Overflow, I learned about the two PowerShell “cmdlets” that would be most useful here: Set-Content and Add-Content.

The text of the script is below. What this script does is recursively search through the file path in line 1, choosing only files that have the extension after the filter switch (.js in this case). Looping through these file names, each file is read into memory (using Get-Content). The root of the file is then removed with the first replace command, and for aesthetics, I chose to change backslashes into forward slashes with the second one (lines 4 and 5). Notice that backslashes must be escaped by using an extra backslash, whereas forward slashes are not escaped. Also, in case you’re wondering, the backtick-n (`n) is the newline character in PowerShell. The Set-Content cmdlet is used to add the “$newline” string and then the original file content. The Add-Content cmdlet is then used to add the line marking the end of the file.

Get-ChildItem "C:\Folder\Subfolder" -recurse -Filter *.js | `
Foreach-Object{
    $content = Get-Content $_.FullName
    $fullname = $_.FullName -replace "C:\\Folder\\Subfolder", ""
    $fullname = $fullname -replace "\\", "/"

    $newline = "// file: " + $fullname + " `n"
    Set-Content $_.FullName -value $newline, $content
    $endline = "// end of file: " + $fullname + " `n"
    Add-Content $_.FullName $endline
}

One Reply to “Adding Lines to the Beginning and Ending of Files Using PowerShell”

Leave a Reply