创建包含文件方法

所以这个功能的主要目标是:

  • 是独立的,因为它需要在主 VbScript 文件中编写,并且不能在包含的文件中(因为它定义了 include 函数)
  • 如果出现问题(例如,包含的文件,发生的错误,……),请提供足够的信息
  • 包含一次文件,只包含一次以避免包含循环。
' *************************************************************************************************
'! Includes a VbScript file
'! @param p_Path    The path of the file to include
' *************************************************************************************************
Sub IncludeFile(p_Path)
    ' only loads the file once
    If std_internal_LibFiles.Exists(p_Path) Then
        Exit Sub
    End If
    
    ' registers the file as loaded to avoid to load it multiple times
    std_internal_LibFiles.Add p_Path, p_Path

    Dim objFso, objFile, strFileContent, strErrorMessage
    Set objFso = CreateObject("Scripting.FileSystemObject")
    
    ' opens the file for reading
    On Error Resume Next
    Set objFile = objFso.OpenTextFile(p_Path)
    If Err.Number <> 0 Then
        ' saves the error before reseting it
        strErrorMessage = Err.Description & " (" &  Err.Source & " " & Err.Number & ")"
        On Error Goto 0
        Err.Raise -1, "ERR_OpenFile", "Cannot read '" & p_Path & "' : " & strErrorMessage
    End If
    
    ' reads all the content of the file
    strFileContent = objFile.ReadAll
    If Err.Number <> 0 Then
        ' saves the error before reseting it
        strErrorMessage = Err.Description & " (" &  Err.Source & " " & Err.Number & ")"
        On Error Goto 0
        Err.Raise -1, "ERR_ReadFile", "Cannot read '" & p_Path & "' : " & strErrorMessage
    End If
    
    ' this allows to run vbscript contained in a string
    ExecuteGlobal strFileContent
    If Err.Number <> 0 Then
        ' saves the error before reseting it
        strErrorMessage = Err.Description & " (" &  Err.Source & " " & Err.Number & ")"
        On Error Goto 0
        Err.Raise -1, "ERR_Include", "An error occurred while including '" & p_Path & "' : " & vbCrlf & strErrorMessage
    End If
End Sub