Skip to content

Instantly share code, notes, and snippets.

@lboulard
Created February 18, 2021 12:11
Show Gist options
  • Save lboulard/0425a837686cf02328c204ff40cda3e7 to your computer and use it in GitHub Desktop.
Save lboulard/0425a837686cf02328c204ff40cda3e7 to your computer and use it in GitHub Desktop.
@FOR /F %%t IN ('cscript //nologo //b %~dp0reset-env.vbs') DO @(
@CALL "%%t"
@DEL /F /Q "%%t"
)
Set wshShell = WScript.CreateObject("WScript.Shell")
If InStr( LCase( WScript.FullName ), "cscript.exe" ) = 0 Then
WScript.Echo "Required cscript.exe to work"
WScript.Quit
End If
Set fso = CreateObject("Scripting.FileSystemObject")
if WScript.Arguments.Count > 0 then
filename = WScript.Arguments.Item(0)
Else
filename = fso.GetSpecialFolder(2) & "\" & fso.GetTempName() & ".bat"
End If
WScript.Stdout.WriteLine filename
Set outputFile = fso.CreateTextFile(filename, TRUE)
outputFile.WriteLine("@REM " & filename)
Const dq = """"
Set systemEnv = wshShell.Environment("SYSTEM")
For Each strItem in systemEnv
t = Left(strItem, 5)
if StrComp(t, "PATH=", vbTextCompare) <> 0 Then
outputFile.WriteLine("@SET " & dq & strItem & dq)
else
systemPath = Mid(strItem, 6)
End If
Next
Set userEnv = wshShell.Environment("USER")
For Each strItem in userEnv
t = Left(strItem, 5)
if StrComp(t, "PATH=", vbTextCompare) <> 0 Then
outputFile.WriteLine("@SET " & dq & strItem & dq)
else
userPath = Mid(strItem, 6)
End If
Next
' Reinject all path entries in PATH defined before system paths
Set processEnv = wshShell.Environment("PROCESS")
processPath = processEnv("PATH")
systemRoot = Split(systemPath, ";")(0)
systemRoot = wshShell.ExpandEnvironmentStrings(systemRoot)
Dim volatilePaths
volatilePaths = Array()
For Each pathname in Split(processPath, ";")
if StrComp(pathname, systemRoot, vbTextCompare) = 0 Then
Exit For
End If
n = UBound(volatilePaths) + 1
ReDim Preserve volatilePaths(n)
volatilePaths(n) = pathname
Next
For Each pathname in volatilePaths
systemPath = pathname & ";" & systemPath
Next
outputFile.WriteLine("@SET " & dq & "PATH=" & systemPath & dq)
outputFile.WriteLine("@SET " & dq & "PATH=%PATH%;" & userPath & dq)
outputFile.Close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment