Q:

Determine if PowerShell script has been run from the desktop or command line

Windows Explorer (desktop) has the ability to run a PowerShell script by right-clicking and selecting "Run with PowerShell". However, as the window is closed when the script has finished, any messages are lost. So one could stick a "Press any key" at the end. However, that would be very annoying when run from the PowerShell command prompt.
Is there a way for PowerShell to determine where it was run from? Specifically, the desktop?

A:

Run with PowerShells $myinvocation.line is taken from corresponding registry key. For instance, on (my) Windows 8.1 with PS version 5.1:
PS D:\PShell> $auxRegKey='\SOFTWARE\Classes\Microsoft.PowerShellScript.1\Shell\0\Command'
PS D:\PShell> (get-itemproperty -literalpath HKLM:$auxRegKey).'(default)'
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & '%1'"
PS D:\PShell>

The following code snippet could help:
'script ouput here'
$auxRegKey='\SOFTWARE\Classes\Microsoft.PowerShellScript.1\Shell\0\Command'
$auxRegVal=(get-itemproperty -literalpath HKLM:$auxRegKey).'(default)'
$auxRegCmd=$auxRegVal.Split(' ',3)[2].Replace('%1', $MyInvocation.MyCommand.Definition)
if ("`"$($myinvocation.Line)`"" -eq $auxRegCmd) {
    $MyInvocation.MyCommand.Definition + ': supposedly run via explorer right click'
    $x = Read-Host
} else {
    $MyInvocation.MyCommand.Definition + ': run from CLI'    # optional
}

The script says supposedly because we could imagine following (improbable) command from an open cmd window (or even its equivalent from PowerShell prompt):
==> "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & 'D:\PShell\SF\q866281.ps1'"
script ouput here
D:\PShell\SF\q866281.ps1: supposedly run via explorer right click

==>

