How to prepend to a file in PowerShell?

Question:

I’m generating two files, userscript.meta.js and userscript.user.js. I need the output of userscript.meta.js to be placed at the very beginning of userscript.user.js.

Add-Content doesn’t seem to accept a parameter to prepend and Get-Content | Set-Content will fail because userscript.user.js is being used by Get-Content.

I’d rather not create an intermediate file if it’s physically possible to have a clean solution.

How to achieve this?

Answer:

The Subexpression operator $( ) can evaluate both Get-Content statements which are then enumerated and passed through the pipeline to Set-Content:

Consider using the Absolute Path of the files if your current directory is not where those files are.


An even more simplified approach than the above would be to put the paths in the desired order since both, the -Path and -LiteralPath parameters can take multiple values:


And in case you want to get rid of excess leading or trailing white-space, you can include the String.Trim Method:

Source:

How to prepend to a file in PowerShell? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply