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

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

==>

There is a variable named $myinvocation will return a InvocationInfo Class object. It contains various information about how the script was invoked. https://msdn.microsoft.com/en-us/library/system.management.automation.invocationinfo(v=vs.85).aspx

You could do something like this to reach your goal.

"hello world"
if ($myinvocation.line) {
    "run from cli"
} else {
    "run via explorer right click"
    $x = read-host
}

Tags:

Powershell