I recently ran a 3rd party script that ran "cmd" inside of it, thus increasing the nesting depth of my cmd window (making my history and DOSKey macros unavailable in the process). So I was wondering if there's an equivalent of $SHLVL or some other way to determine this situation? I suppose I could just up-arrow to see if my history is still there, but someday I might need this from a script.
There does not appear to be anything different when I review the output of "set". Thanks!
EDIT Changed code to list PIDs.
Edit 2 Changed code to output the level as %errorlevel%
See https://docs.microsoft.com/en-us/windows/console/getconsoleprocesslist
CountConsoleProcess.vb
imports System.Runtime.InteropServices
Public Module MyApplication
Public Declare Function GetConsoleProcessList Lib "Kernel32" (ByRef ProcessList as Integer, ByVal Count as Integer) As Integer
Public Sub Main ()
Dim ProcessList(0 To 9) As Integer
Dim Count As Integer
Dim Ret As Integer
Dim x as Integer
Dim ColItems as Object
Dim objWMIService As Object
objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Count = 10
'subtract one to account for this program
Ret = GetConsoleProcessList(ProcessList(0), 10) - 1
Console.Writeline("Level = " & Ret)
For x = Ret to 1 step -1
colItems = objWMIService.ExecQuery("Select * From Win32_Process where ProcessID=" & ProcessList(x))
For Each objItem in colItems
Console.writeline("PID : " & objItem.ProcessID & " Command line : " & objItem.CommandLine)
Next
Next
Environment.ExitCode = Ret
End Sub
End Module
CountConsoleProcess.bat
C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc "%~dp0\CountConsoleProcess.vb" /debug:full /out:"%~dp0\CountConsoleProcess.exe" /target:exe
pause
ConsoleTest.Bat
REM Showing error level
"C:\Users\User\Desktop\ConsoleTest.bat"
Echo %errorlevel%
pause
And to use (after doing a cmd /k
so their are two CMDs running). The first is the current PID.
Microsoft Windows [Version 10.0.10240]
(c) 2015 Microsoft Corporation. All rights reserved.
C:\Windows\system32>cmd /k echo hello world
hello world
C:\Windows\system32>"C:\Users\User\Desktop\ConsoleTest.bat"
C:\Windows\system32>"C:\Users\User\Desktop\Console.exe"
Level = 2
PID : 6848 Command line : "C:\Windows\System32\cmd.exe"
PID : 7824 Command line : cmd /k echo hello world
C:\Windows\system32>Echo 2
2
C:\Windows\system32>
And to add the current folder to the path
_AddThisFolderToPath.bat
Setx path "%path%;%~dp0"
Pause