How to detect Powershell nesting within Powershell?

powershell

Solution

There is no such a magic variable, more likely. But it is possible to get this information:

$me = Get-WmiObject -Query "select * from Win32_Process where Handle=$pid"
$parent = Get-Process -Id $me.ParentProcessId
if ($parent.ProcessName -eq 'powershell') {
    'nested, called from powershell'
}
elseif ($parent.ProcessName -eq 'cmd') {
    'nested, called from cmd'
}
else {
    'not nested'
}

Problem

Is it possible to detect from within Powershell whether it is a nested shell? If I open a Powershell or cmd.exe window, and then type `powershell` <enter> in there, is there a magic $host.somevariable I can query to find out if it is an "inner" shell?

Original source