Skip to content

Commit

Permalink
Merge pull request #2756 from corbob/update-refreshenv
Browse files Browse the repository at this point in the history
(#1392) Update refreshenv to detect when not in cmd shell
  • Loading branch information
vexx32 authored Sep 30, 2022
2 parents 44c5283 + 66baa8f commit e35fe2b
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions src/chocolatey.resources/redirects/RefreshEnv.cmd
Original file line number Diff line number Diff line change
@@ -1,3 +1,66 @@
:: Code generously provided by @beatcracker: https://github.com/beatcracker/detect-batch-subshell
@echo off

setlocal EnableDelayedExpansion

:: Dequote path to command processor and this script path
set ScriptPath=%~0
set CmdPath=%COMSPEC:"=%

:: Get command processor filename and filename with extension
for %%c in (!CmdPath!) do (
set CmdExeName=%%~nxc
set CmdName=%%~nc
)

:: Get this process' PID
:: Adapted from: http://www.dostips.com/forum/viewtopic.php?p=22675#p22675
set "uid="
for /l %%i in (1 1 128) do (
set /a "bit=!random!&1"
set "uid=!uid!!bit!"
)

for /f "tokens=2 delims==" %%i in (
'wmic Process WHERE "Name='!CmdExeName!' AND CommandLine LIKE '%%!uid!%%'" GET ParentProcessID /value'
) do (
rem Get commandline of parent
for /f "tokens=1,2,*" %%j in (
'wmic Process WHERE "Handle='%%i'" GET CommandLine /value'
) do (

rem Strip extra CR's from wmic output
rem http://www.dostips.com/forum/viewtopic.php?t=4266
for /f "delims=" %%x in ("%%l") do (
rem Dequote path to batch file, if any (3rd argument)
set ParentScriptPath=%%x
set ParentScriptPath=!ParentScriptPath:"=!
)

rem Get parent process path
for /f "tokens=2 delims==" %%y in ("%%j") do (
rem Dequote parent path
set ParentPath=%%y
set ParentPath=!ParentPath:"=!

rem Handle different invocations: C:\Windows\system32\cmd.exe , cmd.exe , cmd
for %%p in (!CmdPath! !CmdExeName! !CmdName!) do (
if !ParentPath!==%%p set IsCmdParent=1
)

rem Check if we're running in cmd.exe with /c switch and this script path as argument
if !IsCmdParent!==1 if %%k==/c if "!ParentScriptPath!"=="%ScriptPath%" set IsExternal=1
)
)
)

if !IsExternal!==1 (
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.
exit 1
)

endlocal
:: End code from @beatcracker
@echo off
::
:: RefreshEnv.cmd
Expand Down

0 comments on commit e35fe2b

Please sign in to comment.