Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect Powershell nesting within Powershell?

Tags:

powershell

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?

like image 257
scobi Avatar asked Dec 07 '10 19:12

scobi


People also ask

Can you have nested try catch in PowerShell?

A try-catch-finally statement can be nested beneath another. This is most appropriate when a different approach is required by a smaller section of code. A script perform setup actions, then working on a number of objects in a loop is a good example of one that might require more than one try-catch statement.

Can you nest functions in PowerShell?

In Windows PowerShell® Workflow, you can include functions and nested workflows to reuse and organize the commands in a script workflow. This topic explains the rules for creating and calling nested functions and workflows.

What is $_ PsIsContainer?

The second command where { $_. PsIsContainer -eq $false } uses the PsIsContainer property of all file system objects to select only files, which have a value of False ( $false ) in their PsIsContainer property.

What is %{ in PowerShell?

% alias for ForEach-Object. The % symbol represents the ForEach-Object cmdlet. It allows you to perform an action against multiple objects when that action normally only works on one object at a time.


1 Answers

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'
}
like image 108
Roman Kuzmin Avatar answered Sep 21 '22 23:09

Roman Kuzmin