Difference between console and running a script

Welcome Forums General PowerShell Q&A Difference between console and running a script

Viewing 1 reply thread
  • Author
    • #203204
      Topics: 5
      Replies: 12
      Points: 93
      Rank: Member
      My Google skills are weak today.  I am trying to find documentation of the differences between just running commands in an open PowerShell console windows and running powershell.exe -File .\test.ps1.  I know one difference is some variable are not populated like $PSScriptRoot, $PSCommandPath, $MyInvocation.  I found many postings about the difference between the ISE and a real PowerShell environment.  This is not what I am looking for.
      Side note.  https://www.petri.com/unraveling-mystery-myinvocation is a good explanation for $MyInvocation
      Thank you
    • #203252
      Senior Moderator
      Topics: 3
      Replies: 123
      Points: 653
      Helping Hand
      Rank: Major Contributor

      How to Use a Batch File to Make PowerShell Scripts Easier to Run seems relevant. It talks about steps to make a batch file portable so that a PowerShell script can be executed reliably across different systems.

      However, I couldn’t find anything that directly addresses variables not being populated when executing a script via powershell.exe. I think there may not actually be any such limitations.

      I wrote a simple test script:

      echo "MyInvocation: "$MyInvocation
      echo "PSCommandPath: "$PSCommandPath
      echo "PSScriptRoot: "$PSScriptRoot

      and executed it from the Start menu Run dialog:

      powershell.exe -noprofile C:\fakepath\test.ps1

      All three variables were populated, except for the PSCommandPath and PSScriptRoot properties of $MyInvocation. According to the documentation for $MyInvocation, these properties are distinctly different from the variables $PSCommandPath and $PSScriptRoot. Specifically, the properties are populated only if the current script was called by a previous script. So, in this case they would not be populated because the current script was executed directly (there was no calling script). The $PSCommandPath and $PSScriptRoot variables should contain path information for the current script regardless.

      On a side note, I came across a few interesting things while looking for information, such as Run PowerShell without Powershell.exe and DOSfuscation: Exploring the Depths of Cmd.exe Obfuscation and Detection Techniques.

Viewing 1 reply thread
  • The topic ‘Difference between console and running a script’ is closed to new replies.