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.