Set-Content to $myInvocation.MyCommand.Definition

can a script safely rewrite lines at the beginning of the script file that is currently executing?

I’d like to permanently save variable declarations at the top of the script. kinda like having a small block of declarations that have the same purpose of a separate ini file. I believe this would work with old batch files if you didn’t alter the number of lines

Yes. But please don’t. Self-rewriting code is generally a really bad idea and will lead to a lot of headaches.

Instead, consider storing only default settings in the script itself, and having a file it will read from (or create if it doesn’t exist yet) in order to update its settings. JSON, CSV, or CliXML are all pretty effective, depending on exactly what you need to store. PS has commands for working with all of these:

  • ConvertTo-/ConvertFrom-Json
  • Import-/Export-Csv
  • Import-/Export-CliXml