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
:
1 2 3 4 5 |
$( (Get-Content userscript.meta.js -Raw) (Get-Content userscript.user.js -Raw) ) | Set-Content userscript.user.js |
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:
1 2 3 |
(Get-Content userscript.meta.js, userscript.user.js -Raw) | Set-Content userscript.user.js |
And in case you want to get rid of excess leading or trailing white-space, you can include the
String.Trim
Method:
1 2 3 |
(Get-Content userscript.meta.js, userscript.user.js -Raw).Trim() | Set-Content userscript.user.js |