|
| 1 | +:: Code generously provided by @beatcracker: https://github.com/beatcracker/detect-batch-subshell |
| 2 | +@echo off |
| 3 | + |
| 4 | +setlocal EnableDelayedExpansion |
| 5 | + |
| 6 | +:: Dequote path to command processor and this script path |
| 7 | +set ScriptPath=%~0 |
| 8 | +set CmdPath=%COMSPEC:"=% |
| 9 | + |
| 10 | +:: Get command processor filename and filename with extension |
| 11 | +for %%c in (!CmdPath!) do ( |
| 12 | + set CmdExeName=%%~nxc |
| 13 | + set CmdName=%%~nc |
| 14 | +) |
| 15 | + |
| 16 | +:: Get this process' PID |
| 17 | +:: Adapted from: http://www.dostips.com/forum/viewtopic.php?p=22675#p22675 |
| 18 | +set "uid=" |
| 19 | +for /l %%i in (1 1 128) do ( |
| 20 | + set /a "bit=!random!&1" |
| 21 | + set "uid=!uid!!bit!" |
| 22 | +) |
| 23 | + |
| 24 | +for /f "tokens=2 delims==" %%i in ( |
| 25 | + 'wmic Process WHERE "Name='!CmdExeName!' AND CommandLine LIKE '%%!uid!%%'" GET ParentProcessID /value' |
| 26 | +) do ( |
| 27 | + rem Get commandline of parent |
| 28 | + for /f "tokens=1,2,*" %%j in ( |
| 29 | + 'wmic Process WHERE "Handle='%%i'" GET CommandLine /value' |
| 30 | + ) do ( |
| 31 | + |
| 32 | + rem Strip extra CR's from wmic output |
| 33 | + rem http://www.dostips.com/forum/viewtopic.php?t=4266 |
| 34 | + for /f "delims=" %%x in ("%%l") do ( |
| 35 | + rem Dequote path to batch file, if any (3rd argument) |
| 36 | + set ParentScriptPath=%%x |
| 37 | + set ParentScriptPath=!ParentScriptPath:"=! |
| 38 | + ) |
| 39 | + |
| 40 | + rem Get parent process path |
| 41 | + for /f "tokens=2 delims==" %%y in ("%%j") do ( |
| 42 | + rem Dequote parent path |
| 43 | + set ParentPath=%%y |
| 44 | + set ParentPath=!ParentPath:"=! |
| 45 | + |
| 46 | + rem Handle different invocations: C:\Windows\system32\cmd.exe , cmd.exe , cmd |
| 47 | + for %%p in (!CmdPath! !CmdExeName! !CmdName!) do ( |
| 48 | + if !ParentPath!==%%p set IsCmdParent=1 |
| 49 | + ) |
| 50 | + |
| 51 | + rem Check if we're running in cmd.exe with /c switch and this script path as argument |
| 52 | + if !IsCmdParent!==1 if %%k==/c if "!ParentScriptPath!"=="%ScriptPath%" set IsExternal=1 |
| 53 | + ) |
| 54 | + ) |
| 55 | +) |
| 56 | + |
| 57 | +if !IsExternal!==1 ( |
| 58 | + echo %~nx0 does not work when run from this process. If you're in PowerShell, please 'Import-Module $env:ChocolateyInstall\helpers\chocolateyProfile.psm1' and try again. |
| 59 | + exit 1 |
| 60 | +) |
| 61 | + |
| 62 | +endlocal |
| 63 | +:: End code from @beatcracker |
1 | 64 | @echo off
|
2 | 65 | ::
|
3 | 66 | :: RefreshEnv.cmd
|
|
0 commit comments