- This topic has 1 reply, 2 voices, and was last updated 4 months, 3 weeks ago by
February 12, 2020 at 6:13 pm #203204ParticipantTopics: 5Replies: 12Points: 93Rank: MemberMy 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 $MyInvocationThank you
- This topic was modified 4 months, 3 weeks ago by shawn bequette.
February 12, 2020 at 9:00 pm #203252Senior ModeratorTopics: 3Replies: 123Points: 653Rank: 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 pause
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.
- The topic ‘Difference between console and running a script’ is closed to new replies.