Set-Content to $myInvocation.MyCommand.Definition

Welcome Forums General PowerShell Q&A Set-Content to $myInvocation.MyCommand.Definition

Viewing 1 reply thread
  • Author
    • #188452
      Topics: 2
      Replies: 1
      Points: 29
      Rank: Member

      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

    • #188518
      Topics: 2
      Replies: 513
      Points: 1,322
      Helping Hand
      Rank: Community Hero

      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
Viewing 1 reply thread
  • The topic ‘Set-Content to $myInvocation.MyCommand.Definition’ is closed to new replies.