VBS code to force Symantec Endpoint Protection off

Time:2022-5-8

Using this script, you can rest it at any time. Of course, you can let it continue to work.
The premise is that you must be a local administrator.
This script uses an outdated method of terminating the program: NTSD exe -c q -p ProcessID。 So there was a bat version before. The reason why VBS is used is that it is a little more efficient and there are not too many black windows.
The main idea is: loop termination program + stop service

The code is as follows:

Copy codeThe code is as follows:


‘On Error Resume Next
‘check operating system version
Call CheckOS()
Call MeEncoder()

 

‘program initialization, get parameters
If WScript.Arguments.Count = 0 Then
    Call main()
    WScript.Quit
Else
    Dim strArg, arrTmp
    For Each strArg In WScript.Arguments
        arrTmp = Split(strArg, “=”)
        If UBound( arrTmp ) = 1 Then
            Select Case LCase( arrTmp(0) )
                Case “sep”
                    Call sep( arrTmp(1) )
                Case “process_stop”
                    Call process_stop( arrTmp(1) )
                Case “process_start”
                    Call process_start( arrTmp(1) )
                Case “server_stop”
                    Call server_stop( arrTmp(1) )
                Case “server_start”
                    Call server_start( arrTmp(1) )
                Case “show_tip”
                    Call show_tip( arrTmp(1) )
                Case Else
                    WScript.Quit
            End Select
        End If
    Next
    WScript.Quit
End If

 

‘main program
Sub main()
    If (IsRun(“Rtvscan.exe”, “”) = 1) Or (IsRun(“ccSvcHst.exe”, “”) = 1) Or (IsRun(“SMC.exe”, “”) = 1) Then
        Call SEP_STOP()
    Else
        Call SEP_START()
    End If
End Sub

 

‘run with parameters
Sub sep( strMode )
    Select Case LCase(strMode)
        Case “stop”
            Call SEP_STOP()
        Case “start”
            Call SEP_START()
    End Select
End Sub

 

‘stop SEP ‘
Sub SEP_STOP()

    Set wso = CreateObject(“WScript.Shell”)

    ‘kill other app
    Call process_clear()
    ‘kill sep
    wso.Run “””” & WScript.ScriptFullName & “”” server_stop=””SENS”””, 0, True

    ‘Get Me PID
    Set pid = Getobject(“winmgmts:\\.”).InstancesOf(“Win32_Process”)
    For Each id In pid
        If LCase(id.name) = LCase(“Wscript.exe”) Then
            mepid=id.ProcessID
        End If
    Next

    ‘tips
    wso.Run “””” & WScript.ScriptFullName & “”” show_tip=stop”, 0, False

    ‘stop service
    wso.Run “””” & WScript.ScriptFullName & “”” server_stop=””SENS”””, 0, True
    wso.Run “””” & WScript.ScriptFullName & “”” server_stop=””Symantec AntiVirus”””, 0, True
    wso.Run “””” & WScript.ScriptFullName & “”” server_stop=””ccEvtMgr”””, 0, True
    wso.Run “””” & WScript.ScriptFullName & “”” server_stop=””SmcService”””, 0, True
    wso.Run “””” & WScript.ScriptFullName & “”” server_stop=””SNAC”””, 0, True
    wso.Run “””” & WScript.ScriptFullName & “”” server_stop=””ccSetMgr”””, 0, True

    ‘kill apps
    wso.Run “””” & WScript.ScriptFullName & “”” process_stop=ccApp.exe”, 0, False
    wso.Run “””” & WScript.ScriptFullName & “”” process_stop=ccSvcHst.exe”, 0, False
    wso.Run “””” & WScript.ScriptFullName & “”” process_stop=SNAC.exe”, 0, False
    wso.Run “””” & WScript.ScriptFullName & “”” process_stop=Rtvscan.exe”, 0, False
    wso.Run “””” & WScript.ScriptFullName & “”” process_stop=SescLU.exe”, 0, False
    wso.Run “””” & WScript.ScriptFullName & “”” process_stop=Smc.exe”, 0, False
    wso.Run “””” & WScript.ScriptFullName & “”” process_stop=SmcGui.exe”, 0, False

    ‘wait
    WScript.Sleep 15000

    ‘kill other script
    Set pid = Getobject(“winmgmts:\\.”).InstancesOf(“Win32_Process”)
    For Each ps In pid
        If (LCase(ps.name) = “wscript.exe”) Or (LCase(ps.name) = “cscript.exe”) Then ps.terminate
    Next

    ‘kill other app
    Call process_clear()

    ‘start ?
    ‘Call SEP_START()
End Sub

 

‘restore SEP ‘
Sub SEP_START()
    Set wso = CreateObject(“WScript.Shell”)
    ‘tips
    wso.Run “””” & WScript.ScriptFullName & “”” show_tip=start”, 0, False

    ‘start server
    wso.Run “””” & WScript.ScriptFullName & “”” server_stop=””SENS”””, 0, True
    wso.Run “””” & WScript.ScriptFullName & “”” server_start=””Symantec AntiVirus”””, 0, True
    wso.Run “””” & WScript.ScriptFullName & “”” server_start=””ccEvtMgr”””, 0, True
    wso.Run “””” & WScript.ScriptFullName & “”” server_start=””SmcService”””, 0, True
    wso.Run “””” & WScript.ScriptFullName & “”” server_start=””SNAC”””, 0, True
    wso.Run “””” & WScript.ScriptFullName & “”” server_start=””ccSetMgr”””, 0, True
    Set wso = Nothing
End Sub

 

‘close process
Function process_stop( strAppName )
        Dim i
        For i = 1 To 100
        Set pid = Getobject(“winmgmts:\\.”).InstancesOf(“Win32_Process”)
                For Each id In pid
                        If LCase(id.name) = LCase(strAppName) Then
                                Dim wso
                                Set wso = CreateObject(“WScript.Shell”)
                                wso.run “ntsd.exe -c q -p ” & id.ProcessID, 0, True
                        End If
                Next
        WScript.Sleep 500
        Next
End Function

 

‘stop service
Sub server_stop( byVal strServerName )

    Set wso = CreateObject(“WScript.Shell”)
    wso.run “sc config “”” & strServerName & “”” start= disabled”, 0, True
    wso.run “cmd /c echo Y|net stop “”” & strServerName & “”””, 0, True
    Set wso = Nothing

End Sub

 

‘Start service
Sub server_start( byVal strServerName )

    Set wso = CreateObject(“WScript.Shell”)
    wso.run “sc config “”” & strServerName & “”” start= auto”, 0, True
    wso.run “cmd /c echo Y|net start “”” & strServerName & “”””, 0, True
    Set wso = Nothing

End Sub

 

‘display prompt
Sub show_tip( strType )
    Set wso = CreateObject(“WScript.Shell”)
    Select Case LCase(strType)
        Case “stop”
            wso. Pop Chr (13) + “stop SEP, please wait “+ Chr (13), 20,” stopsep running “, 0 + 64
        Case “start”
            wso. Pop Chr (13) + “starting SEP, please wait “+ Chr (13), 20,” stopsep has stopped “, 0 + 64
    End Select
    Set wso = Nothing
End Sub

 

‘ Clear process
Sub process_clear()
    ‘kill other app
    Set pid = Getobject(“winmgmts:\\.”).InstancesOf(“Win32_Process”)
    For Each ps In pid
        Select Case LCase(ps.name)
            Case “net.exe”
                ps.terminate
            Case “net1.exe”
                ps.terminate
            Case “sc.exe”
                ps.terminate
            Case “ntsd.exe”
                ps.terminate
        End Select
    Next
End Sub

 

 

‘ ====================================================================================================
‘ ****************************************************************************************************
‘* common function
‘* usage: add all the codes in this section to the end of the program, and add the following codes (1 line) to the first line of the program:
‘* dim whoamI, TMPDIR, windir, appdatadir, startupdir, medir, unchost: call getglovar()’ global variable
‘* get support: email to [email protected]
‘* Update Date: 12-10-2012 11:37
‘ ****************************************************************************************************
‘function index
‘command line support:
‘detection environment: is iscmdmode running under CMD
‘simulation command: exist whether a file or folder exists, MD creates a directory, copy copies a file or folder, del deletes a file or folder
‘attrib change file or folder properties, Ping detect network connectivity
‘dialog box:
‘prompt message: warninginfo warning message, tipinfo prompt message, errorinfo error message
‘enter password: GetPassword prompts for password
‘file system:
‘copy, delete and change attributes: refer to “command line support”.
‘INI file processing: reading and writing INI files (Unicode) readiniunicode / writeiniunicode
‘registry processing: regread reads the registry and regwrite writes the registry
‘log processing: writelog writes text log
‘string processing:
‘extract: regexptest
‘procedure:
‘detection: whether isrun is running and whether meisalreadyrun is executing this program
‘execution: run foreground waiting for execution, runhide hidden waiting for execution, runnotwait foreground not waiting for execution, runhidenotwite background not waiting for execution
‘encryption run: meencoder
‘system:
‘version
‘delay: sleep
‘Send key: sendkeys
‘Network:
‘detection: Ping, refer to “command line support”.
‘Connect: file share
‘time: format_ Time format time, nowdatetime current time
‘ ====================================================================================================
‘ ====================================================================================================
‘initialize global variables
‘ Dim WhoAmI, TmpDir, WinDir, AppDataDir, StartupDir, MeDir, UNCHost
Sub GetGloVar()
    WhoAmI = CreateObject( “WScript.Network” ). ComputerName & “\” & CreateObject( “WScript.Network” ). Username ‘user information
    TmpDir = CreateObject(“Scripting.FileSystemObject”). Getspecialfolder (2) & “\” ‘temporary folder path
    WinDir = CreateObject(“wscript.Shell”). Expandenvironmentstrings (“% windir%”) & “\” ‘local% windir% folder path
    AppDataDir = CreateObject(“WScript.Shell”). Specialfolders (“appdata”) & “\” local% appdata% folder path
    StartupDir = CreateObject(“WScript.Shell”). Specialfolders (“startup”) & “\” ‘local startup folder path
Medir = left (wsscript.scriptfullname, InStrRev (wsscript.scriptfullname, “\”) ‘folder path of script
‘when the script is located in the shared directory, get the shared computer name (unchost) and verify the location (if unchost < > “serntf02” then Wscript. Quit)’ to prevent copying to the local operation
    UNCHost = LCase(Mid(WScript.ScriptFullName,InStr(WScript.ScriptFullName,”\\”)+2,InStr(3,WScript.ScriptFullName,”\”,1)-3))
End Sub


‘ ====================================================================================================
‘small function
Sub sleep (stime) ‘delay stime MS
    WScript.Sleep sTime
End Sub
Sub sendkeys (strkey) ‘send key
    CreateObject(“WScript.Shell”).SendKeys strKey
End Sub
‘keycode – Key Code:
‘ Shift +       *Ctrl ^     *Alt %     *BACKSPACE {BACKSPACE}, {BS}, or {BKSP}      *BREAK {BREAK}
‘ CAPS LOCK {CAPSLOCK}      *DEL or DELETE {DELETE} or {DEL}     *DOWN ARROW {DOWN}     *END {END}
‘ ENTER {ENTER}or ~     *ESC {ESC}     *HELP {HELP}   *HOME {HOME}   *INS or INSERT {INSERT} or {INS}
‘ LEFT ARROW {LEFT}     *NUM LOCK {NUMLOCK}    *PAGE DOWN {PGDN}     *PAGE UP {PGUP}    *PRINT SCREEN {PRTSC}
‘ RIGHT ARROW {RIGHT}   *SCROLL LOCK {SCROLLLOCK}      *TAB {TAB}    *UP ARROW {UP}     *F1 {F1}   *F16 {F16}
‘example: switch input method (press shift and Ctrl keys simultaneously during simulation) “+ (^)”; Restart the computer (simulate pressing Ctrl + ESC, u, R): “^ {ESC}ur”.
‘press simultaneously: press shift key while pressing E and C: “+ (EC)”; When pressing e, only press C (not shift): “+ EC”.
‘repeat key: press “X” 10 times: “{x 10}”. There is a space between the key and the number.
‘special characters: send “+” and “^” special control keys: “{+}” and “{^}”
‘note: you can only send keys that press one key repeatedly. For example, you can send “X” 10 times, but not “Ctrl + X” 10 times.  
‘note: the print screen key {prtsc} cannot be sent to the application.
Function appactivate (strwindowtitle) ‘activate the window whose title contains the specified characters, for example, judge whether disk D is opened if appactivate (“(D:)) then
    AppActivate = CreateObject(“WScript.Shell”).AppActivate( strWindowTitle )
End Function


‘ ====================================================================================================
‘showmsg message Popup
Sub WarningInfo( strTitle, strMsg, sTime )
    CreateObject(“wscript.Shell”). Pop strmsg, stime, strTitle, 48 + 4096 ‘prompt information
End Sub
Sub TipInfo( strTitle, strMsg, sTime )
    CreateObject(“wscript.Shell”). Pop strmsg, stime, strTitle, 64 + 4096 ‘prompt information
End Sub
Sub ErrorInfo( strTitle, strMsg, sTime )
    CreateObject(“wscript.Shell”). Pop strmsg, stime, strTitle, 16 + 4096 ‘prompt information
End Sub

‘ ====================================================================================================
‘runapp executor
Sub Run( strCmd )
    CreateObject(“WScript.Shell”). Run strcmd, 1, true ‘normal operation + wait for the program to finish running
End Sub
Sub RunNotWait( strCmd )
    CreateObject(“WScript.Shell”). Run strcmd, 1, false ‘normal operation + do not wait for the program to finish running
End Sub
Sub RunHide( strCmd )
    CreateObject(“WScript.Shell”). Run strcmd, 0, true ‘hide background running + wait for the program to finish running
End Sub
Sub RunHideNotWait( strCmd )
    CreateObject(“WScript.Shell”). Run strcmd, 0, false ‘hide background running + do not wait for the program to finish running
End Sub

‘ ====================================================================================================
‘CMD command set
‘ —————————————————————————————————-
‘ —————————————————————————————————-
‘get CMD output
Function CmdOut(str)
        Set ws = CreateObject(“WScript.Shell”)
        host = WScript.FullName
‘demon note: it doesn’t need to be so complicated here. Lcase (right (host, 11)) is OK
        If LCase( right(host, len(host)-InStrRev(host,”\”)) ) = “wscript.exe” Then
                ws.run “cscript “”” & WScript.ScriptFullName & chr(34), 0
                WScript.Quit
        End If
        Set oexec = ws.Exec(str)
        CmdOut = oExec.StdOut.ReadAll
End Function
‘check whether it runs in CMD mode
Function IsCmdMode()
    IsCmdMode = False
    If (LCase(Right(WScript.FullName,11)) = LCase(“CScript.exe”)) Then IsCmdMode = True
End Function
‘exist detects whether a file or folder exists
Function Exist( strPath )
    Exist = False
    Set fso = CreateObject(“Scripting.FileSystemObject”)
    If ((fso.FolderExists(strPath)) Or (fso.FileExists(strPath))) Then Exist = True
    Set fso = Nothing
End Function
‘ —————————————————————————————————-
‘md create folder path
Sub MD( ByVal strPath )
    Dim arrPath, strTemp, valStart
    arrPath = Split(strPath, “\”)
    If Left(strPath, 2) = “\\” Then    ‘ UNC Path
        valStart = 3
        strTemp = arrPath(0) & “\” & arrPath(1) & “\” & arrPath(2)
    Else                              ‘ Local Path
        valStart = 1
        strTemp = arrPath(0)
    End If
    Set fso = CreateObject(“Scripting.FileSystemObject”)
    For i = valStart To UBound(arrPath)
        strTemp = strTemp & “\” & arrPath(i)
        If Not fso.FolderExists( strTemp ) Then fso.CreateFolder( strTemp )
    Next
    Set fso = Nothing
End Sub
‘ —————————————————————————————————-
‘copy copy file or folder
Sub Copy( ByVal strSource, ByVal strDestination )
On error resume next ‘required
    Set fso = CreateObject(“Scripting.FileSystemObject”)
If (FSO. FileExists (strsource)) then ‘if the source is a file
If (FSO. Folderexists (strdestination)) then ‘if the destination is a folder, add the path suffix backslash “\”
            fso.CopyFile fso.GetFile(strSource).Path, fso.GetFolder(strDestination).Path & “\”, True
Else ‘if the destination is a file, copy it directly
            fso.CopyFile fso.GetFile(strSource).Path, strDestination, True
        End If
End if ‘if the source is a folder, copy the folder
    If (fso.FolderExists(strSource)) Then fso.CopyFolder fso.GetFolder(strSource).Path, fso.GetFolder(strDestination).Path, True
    Set fso = Nothing
End Sub
‘ —————————————————————————————————-
‘del delete file or folder
Sub Del( strPath )
On error resume next ‘required
    Set fso = CreateObject(“Scripting.FileSystemObject”)
    If (fso.FileExists(strPath)) Then
        fso.GetFile( strPath ).attributes = 0
        fso.GetFile( strPath ).delete
    End If
    If (fso.FolderExists(strPath)) Then
        fso.GetFolder( strPath ).attributes = 0
        fso.GetFolder( strPath ).delete
    End If
    Set fso = Nothing
End Sub
‘ —————————————————————————————————-
‘attrib change file attributes
Sub Attrib( strPath, strArgs )    ‘strArgs = [+R | -R] [+A | -A ] [+S | -S] [+H | -H]
    Dim fso, valAttrib, arrAttrib()
    Set fso = CreateObject(“Scripting.FileSystemObject”)
    If (fso.FileExists(strPath)) Then valAttrib = fso.getFile( strPath ).attributes
    If (fso.FolderExists(strPath)) Then valAttrib = fso.getFolder( strPath ).attributes
    If valAttrib = “” Or strArgs = “” Then Exit Sub
Binattrib = dectobin (valattrib) ‘decimal to binary
For I = 0 to 16 ‘binary to 16 bit binary
        ReDim Preserve arrAttrib(i) : arrAttrib(i) = 0
        If i > 16-Len(binAttrib) Then arrAttrib(i) = Mid(binAttrib, i-(16-Len(binAttrib)), 1)
    Next
If instr (1, lcase (strargs), “+ R”, 1) then arrattrib (16-0) = 1 ‘readonly 1 read only file.
    If Instr(1, LCase(strArgs), “-r”, 1) Then arrAttrib(16-0) = 0
If instr (1, lcase (strargs), “+ H”, 1) then arrattrib (16-1) = 1 ‘hidden 2 hidden file.
    If Instr(1, LCase(strArgs), “-h”, 1) Then arrAttrib(16-1) = 0
If instr (1, lcase (strargs), “+ s”, 1) then arrattrib (16-2) = 1 ‘system 4 system file.
    If Instr(1, LCase(strArgs), “-s”, 1) Then arrAttrib(16-2) = 0
If instr (1, lcase (strargs), “+ a”, 1) then arrattrib (16-5) = 1 ‘archive 32 files changed since the last backup.
    If Instr(1, LCase(strArgs), “-a”, 1) Then arrAttrib(16-5) = 0
Valattrib = bintodec (join (arrattrib, “”) ‘binary to decimal
    If (fso.FileExists(strPath)) Then fso.getFile( strPath ).attributes = valAttrib
    If (fso.FolderExists(strPath)) Then fso.getFolder( strPath ).attributes = valAttrib
    Set fso = Nothing
End Sub
Function dectobin (ByVal number) ‘decimal to binary
   Dim remainder
   remainder = number
   Do While remainder > 0
      DecToBin = CStr(remainder Mod 2) & DecToBin
      remainder = remainder \ 2
   Loop
End Function
Function bintodec (ByVal binstr) ‘binary to decimal
   Dim i
   For i = 1 To Len(binStr)
      BinToDec = BinToDec + (CInt(Mid(binStr, i, 1)) * (2 ^ (Len(binStr) – i)))
   Next
End Function
‘ —————————————————————————————————-
‘Ping determines whether the network is connected
Function Ping(host)
    On Error Resume Next
    Ping = False :   If host = “” Then Exit Function
    Set objPing = GetObject(“winmgmts:{impersonationLevel=impersonate}”).ExecQuery(“select * from Win32_PingStatus where address = ‘” & host & “‘”)
    For Each objStatus in objPing
        If objStatus.ResponseTime >= 0 Then Ping = True :   Exit For
    Next
    Set objPing = nothing
End Function

‘ ====================================================================================================
‘get the current date and time and format it
Function NowDateTime()
‘myweek = “week” & right (WeekdayName (weekday (date()), 1) & “”
    MyWeek = “”
    NowDateTime = MyWeek & Format_Time(Now(),2) & ” ” & Format_Time(Now(),3)
End Function
Function Format_Time(s_Time, n_Flag)
    Dim y, m, d, h, mi, s
    Format_Time = “”
    If IsDate(s_Time) = False Then Exit Function
    y = cstr(year(s_Time))
    m = cstr(month(s_Time))
        If len(m) = 1 Then m = “0” & m
    d = cstr(day(s_Time))
        If len(d) = 1 Then d = “0” & d
    h = cstr(hour(s_Time))
        If len(h) = 1 Then h = “0” & h
    mi = cstr(minute(s_Time))
        If len(mi) = 1 Then mi = “0” & mi
    s = cstr(second(s_Time))
        If len(s) = 1 Then s = “0” & s
    Select Case n_Flag
        Case 1
            Format_Time = y  & m & d  & h  & mi  & s    ‘ yyyy-mm-dd hh:mm:ss
        Case 2
            Format_Time = y & “-” & m & “-” & d    ‘ yyyy-mm-dd
        Case 3
            Format_Time = h & “:” & mi & “:” & s   ‘ hh:mm:ss
        Case 4
            Format_ Time = y & “year” & M & “month” & D & “day” ‘yyyy mm MM DD
        Case 5
            Format_Time = y & m & d    ‘ yyyymmdd
    End Select
End Function


‘ ====================================================================================================
‘check whether the string conforms to the regular expression
‘Msgbox Join(RegExpTest( “[A-z]+-[A-z]+”, “a-v d-f b-c” ,”Value”), VbCrLf)
‘Msgbox RegExpTest( “[A-z]+-[A-z]+”, “a-v d-f b-c” ,”Count”)
‘Msgbox RegExpTest( “[A-z]+-[A-z]+”, “a-v d-f b-c” ,””)
Function RegExpTest(patrn, strng, mode)
Dim regex, match, matches’ create variables.
Set regex = new regexp ‘establish regular expression.
        regEx. Pattern = pattern ‘sets the pattern.
        regEx. Ignorecase = true ‘sets whether characters are case sensitive.
        regEx. Global = true ‘set global availability.
    Dim RetStr, arrMatchs(), i  :  i = -1
    Set Matches = regEx. Execute (strng) ‘execute the search.
For each match in matches’ traverse the matching set.
        i = i + 1
ReDim preserve arrmatches (I) ‘dynamic array: the array changes with the loop
        arrMatchs(i) = Match.Value
        RetStr = RetStr & “Match found at position ” & Match.FirstIndex & “. Match Value is ‘” & Match.Value & “‘.” & vbCRLF
    Next
If lcase (mode) = lcase (“value”) then regexptest = arrmatches’ returns all data that matches the expression in an array
    If LCase(mode) = LCase(“Count”) Then RegExpTest = Matches. Count ‘returns the total number of all data matching the expression as an integer
If isempty (regexptest) then regexptest = retstr ‘returns all matching results
End Function


‘ ====================================================================================================
‘read and write registry
Function RegRead( strKey )
    On Error Resume Next
    Set wso = CreateObject(“WScript.Shell”)
    RegRead = wso.RegRead( strKey )    ‘strKey = “HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\DocTip”
    If IsArray( RegRead ) Then RegRead = Join(RegRead, VbCrLf)
    Set wso = Nothing
End Function
‘write registry
Function RegWrite( strKey, strKeyVal, strKeyType )
    On Error Resume Next
    Dim fso, strTmp
    RegWrite = Flase
    Set wso = CreateObject(“WScript.Shell”)
    wso.RegWrite strKey, strKeyVal, strKeyType
    strTmp = wso.RegRead( strKey )
    If strTmp <> “” Then RegWrite = True
    Set wso = Nothing
End Function

‘ ====================================================================================================
‘read write INI file (Unicode) readiniunicode / writeiniunicode
‘ This subroutine writes a value to an INI file

‘ Arguments:
‘ myFilePath  [string]  the (path and) file name of the INI file
‘ mySection   [string]  the section in the INI file to be searched
‘ myKey           [string]  the key whose value is to be written
‘ myValue         [string]  the value to be written (myKey will be
‘                                           deleted if myValue is <DELETE_THIS_VALUE>)

‘ Returns:
‘ N/A

‘ CAVEAT:         WriteIni function needs ReadIniUnicode function to run

‘ Written by Keith Lacelle
‘ Modified by Denis St-Pierre, Johan Pol and Rob van der Woude
Sub WriteIniUnicode( myFilePath, mySection, myKey, myValue )
        On Error Resume Next

        Const ForReading   = 1
        Const ForWriting   = 2
        Const ForAppending = 8
        Const TristateTrue = -1

        Dim blnInSection, blnKeyExists, blnSectionExists, blnWritten
        Dim intEqualPos
        Dim objFSO, objNewIni, objOrgIni, wshShell
        Dim strFilePath, strFolderPath, strKey, strLeftString
        Dim strLine, strSection, strTempDir, strTempFile, strValue

        strFilePath = Trim( myFilePath )
        strSection  = Trim( mySection )
        strKey          = Trim( myKey )
        strValue        = Trim( myValue )

        Set objFSO   = CreateObject( “Scripting.FileSystemObject” )
        Set wshShell = CreateObject( “WScript.Shell” )

        strTempDir  = wshShell.ExpandEnvironmentStrings( “%TEMP%” )
        strTempFile = objFSO.BuildPath( strTempDir, objFSO.GetTempName )

        Set objOrgIni = objFSO.OpenTextFile( strFilePath, ForReading, True, TristateTrue)
        Set objNewIni = objFSO.OpenTextFile( strTempFile, ForWriting, True, TristateTrue)
        ‘Set objNewIni = objFSO.CreateTextFile( strTempFile, False, False )

        blnInSection         = False
        blnSectionExists = False
        ‘ Check if the specified key already exists
        blnKeyExists         = ( ReadIniUnicode( strFilePath, strSection, strKey ) <> “” )
        blnWritten           = False

        ‘ Check if path to INI file exists, quit if not
        strFolderPath = Mid( strFilePath, 1, InStrRev( strFilePath, “\” ) )
        If Not objFSO.FolderExists ( strFolderPath ) Then
                REM WScript.Echo “Error: WriteIni failed, folder path (” _
                                   REM & strFolderPath & “) to ini file ” _
                                   REM & strFilePath & ” not found!”
                Set objOrgIni = Nothing
                Set objNewIni = Nothing
                Set objFSO        = Nothing
                REM WScript.Quit 1
                Exit Sub
        End If

        While objOrgIni.AtEndOfStream = False
                strLine = Trim( objOrgIni.ReadLine )
                If blnWritten = False Then
                        If LCase( strLine ) = “[” & LCase( strSection ) & “]” Then
                                blnSectionExists = True
                                blnInSection = True
                        ElseIf InStr( strLine, “[” ) = 1 Then
                                blnInSection = False
                        End If
                End If

                If blnInSection Then
                        If blnKeyExists Then
                                intEqualPos = InStr( 1, strLine, “=”, vbTextCompare )
                                If intEqualPos > 0 Then
                                        strLeftString = Trim( Left( strLine, intEqualPos – 1 ) )
                                        If LCase( strLeftString ) = LCase( strKey ) Then
                                                ‘ Only write the key if the value isn’t empty
                                                ‘ Modification by Johan Pol
                                                If strValue <> “<DELETE_THIS_VALUE>” Then
                                                        objNewIni.WriteLine strKey & “=” & strValue
                                                End If
                                                blnWritten   = True
                                                blnInSection = False
                                        End If
                                End If
                                If Not blnWritten Then
                                        objNewIni.WriteLine strLine
                                End If
                        Else
                                objNewIni.WriteLine strLine
                                        ‘ Only write the key if the value isn’t empty
                                        ‘ Modification by Johan Pol
                                        If strValue <> “<DELETE_THIS_VALUE>” Then
                                                objNewIni.WriteLine strKey & “=” & strValue
                                        End If
                                blnWritten   = True
                                blnInSection = False
                        End If
                Else
                        objNewIni.WriteLine strLine
                End If
        Wend

        If blnSectionExists = False Then ‘ section doesn’t exist
                objNewIni.WriteLine
                objNewIni.WriteLine “[” & strSection & “]”
                        ‘ Only write the key if the value isn’t empty
                        ‘ Modification by Johan Pol
                        If strValue <> “<DELETE_THIS_VALUE>” Then
                                objNewIni.WriteLine strKey & “=” & strValue
                        End If
        End If

        objOrgIni.Close
        objNewIni.Close

        ‘ Delete old INI file
        objFSO.DeleteFile strFilePath, True
        ‘ Rename new INI file
        objFSO.MoveFile strTempFile, strFilePath

        Set objOrgIni = Nothing
        Set objNewIni = Nothing
        Set objFSO        = Nothing
        Set wshShell  = Nothing

End Sub
Function ReadIniUnicode( myFilePath, mySection, myKey )
        On Error Resume Next

        Const ForReading   = 1
        Const ForWriting   = 2
        Const ForAppending = 8
        Const TristateTrue = -1

        Dim intEqualPos
        Dim objFSO, objIniFile
        Dim strFilePath, strKey, strLeftString, strLine, strSection

        Set objFSO = CreateObject( “Scripting.FileSystemObject” )

        ReadIniUnicode         = “”
        strFilePath = Trim( myFilePath )
        strSection  = Trim( mySection )
        strKey          = Trim( myKey )

        If objFSO.FileExists( strFilePath ) Then
                Set objIniFile = objFSO.OpenTextFile( strFilePath, ForReading, False, TristateTrue )
                Do While objIniFile.AtEndOfStream = False
                        strLine = Trim( objIniFile.ReadLine )

                        ‘ Check if section is found in the current line
                        If LCase( strLine ) = “[” & LCase( strSection ) & “]” Then
                                strLine = Trim( objIniFile.ReadLine )

                                ‘ Parse lines until the next section is reached
                                Do While Left( strLine, 1 ) <> “[“
                                        ‘ Find position of equal sign in the line
                                        intEqualPos = InStr( 1, strLine, “=”, 1 )
                                        If intEqualPos > 0 Then
                                                strLeftString = Trim( Left( strLine, intEqualPos – 1 ) )
                                                ‘ Check if item is found in the current line
                                                If LCase( strLeftString ) = LCase( strKey ) Then
                                                        ReadIniUnicode = Trim( Mid( strLine, intEqualPos + 1 ) )
                                                        ‘ In case the item exists but value is blank
                                                        If ReadIniUnicode = “” Then
                                                                ReadIniUnicode = ” “
                                                        End If
                                                        ‘ Abort loop when item is found
                                                        Exit Do
                                                End If
                                        End If

                                        ‘ Abort if the end of the INI file is reached
                                        If objIniFile.AtEndOfStream Then Exit Do

                                        ‘ Continue with next line
                                        strLine = Trim( objIniFile.ReadLine )
                                Loop
                        Exit Do
                        End If
                Loop
                objIniFile.Close
        Else
                REM WScript.Echo strFilePath & ” doesn’t exists. Exiting…”
                REM Wscript.Quit 1
                REM Msgbox strFilePath & ” doesn’t exists. Exiting…”
                Exit Function
        End If
End Function

‘ ====================================================================================================
‘write text log
Sub WriteLog(str, file)
    If (file = “”) Or (str = “”) Then Exit Sub
    str = NowDateTime & ”   ” & str & VbCrLf
    Dim fso, wtxt
Const forappending = 8 ‘forreading = 1 (read-only, no write), forwriting = 2 (write only, no read), forappending = 8 (write at the end of the file)
Const create = true ‘Boolean value, whether to create a new file when filename does not exist. Allow creation to be true, otherwise false. The default value is false.
    Const TristateTrue = -1        ‘TristateUseDefault = -2 (SystemDefault), TristateTrue = -1 (Unicode), TristateFalse = 0 (ASCII)

    On Error Resume  Next
    Set fso = CreateObject(“Scripting.filesystemobject”)
    set wtxt = fso.OpenTextFile(file, ForAppending, Create, TristateTrue)
    wtxt.Write str
    wtxt.Close()
    set fso = Nothing
    set wtxt = Nothing
End Sub

 

‘ ====================================================================================================
‘program control
‘check whether it works
Function IsRun(byVal AppName, byVal AppPath)   ‘ Eg: Call IsRun(“mshta.exe”, “c:\test.hta”)
    IsRun = 0 : i = 0
    For Each ps in GetObject(“winmgmts:\\.\root\cimv2:win32_process”).instances_
        IF LCase(ps.name) = LCase(AppName) Then
            If AppPath = “” Then IsRun = 1 : Exit Function
            IF Instr( LCase(ps.CommandLine) , LCase(AppPath) ) Then i = i + 1
        End IF
    Next
    IsRun = i
End Function
‘ —————————————————————————————————-
‘detect whether it runs repeatedly
Function MeIsAlreadyRun()
    MeIsAlreadyRun = False
    If ((IsRun(“WScript.exe”,WScript.ScriptFullName)>1) Or (IsRun(“CScript.exe”,WScript.ScriptFullName)>1)) Then MeIsAlreadyRun = True
End Function
‘ —————————————————————————————————-
‘close process
Sub Close_Process(ProcessName)
    ‘On Error Resume Next
    For each ps in getobject(“winmgmts:\\.\root\cimv2:win32_process”). instances_ ‘loop process
        If Ucase(ps.name)=Ucase(ProcessName) Then
            ps.terminate
        End if
    Next
End Sub


‘ ====================================================================================================
‘system
‘check operating system version
Sub CheckOS()
    If LCase(OSVer()) <> “xp” Then
Msgbox “this operating system is not supported!”, 48 + 4096, “warning”
        WScript. Quit ‘quit the program
    End If
End Sub
‘ —————————————————————————————————-
‘get operating system version
Function OSVer()
    Dim objWMI, objItem, colItems
    Dim strComputer, VerOS, VerBig, Ver9x, Version9x, OS, OSystem
    strComputer = “.”
    Set objWMI = GetObject(“winmgmts:\\” & strComputer & “\root\cimv2”)
    Set colItems = objWMI.ExecQuery(“Select * from Win32_OperatingSystem”,,48)
    For Each objItem in colItems
        VerBig = Left(objItem.Version,3)
    Next
    Select Case VerBig
        Case “6.1” OSystem = “Win7”
        Case “6.0” OSystem = “Vista”
        Case “5.2” OSystem = “Windows 2003”
        Case “5.1” OSystem = “XP”
        Case “5.0” OSystem = “W2K”
        Case “4.0” OSystem = “NT4.0”
        Case Else OSystem = “Unknown”
                  If CInt(Join(Split(VerBig,”.”),””)) < 40 Then OSystem = “Win9x”
    End Select
    OSVer = OSystem
End Function
‘ —————————————————————————————————-
‘get operating system language
Function language()
    Dim strComputer, objWMIService, colItems, strLanguageCode, strLanguage
    strComputer = “.”
    Set objWMIService = GetObject(“winmgmts://” &strComputer &”/root/CIMV2″)
    Set colItems = objWMIService.ExecQuery(“SELECT * FROM Win32_OperatingSystem”)
    For Each objItem In colItems
        strLanguageCode = objItem.OSLanguage
    Next
    Select Case strLanguageCode
        Case “1033” strLanguage = “en”
        Case “2052” strLanguage = “chs”
        Case Else  strLanguage = “en”
    End Select
    language = strLanguage
End Function

‘ ====================================================================================================
‘Encrypt itself
Sub MeEncoder()
    Dim MeAppPath, MeAppName, MeAppFx, MeAppEncodeFile, data
    MeAppPath = left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName,”\”))
    MeAppName = Left( WScript.ScriptName, InStrRev(WScript.ScriptName,”.”) – 1 )
    MeAppFx = Right(WScript.ScriptName, Len(WScript.ScriptName) – InStrRev(WScript.ScriptName,”.”) + 1 )
    MeAppEncodeFile = MeAppPath & MeAppName & “.s.vbe”
    If Not ( LCase(MeAppFx) = LCase(“.vbs“) ) Then Exit Sub
    Set fso = CreateObject(“Scripting.FileSystemObject”)
    data = fso.OpenTextFile(WScript.ScriptFullName, 1, False, -1).ReadAll
    data = CreateObject(“Scripting.Encoder”).EncodeScriptFile(“.vbs”, data, 0, “VBScript”)
    fso.OpenTextFile(MeAppEncodeFile, 2, True, -1).Write data
Msgbox “after encoding, the file is generated to:” & vbcrlf & vbcrlf & meappencodefile, 64 + 4096, Wscript ScriptName
    Set fso = Nothing
    WScript.Quit
End Sub