サーチ…


前書き

WindowsシェルでVbScriptを実行すると、ファイルを組み込む機能が組み込まれていないため、コードを別のファイルに編成して、そのためのメソッドを作成する必要があります。

備考

IncludeFile(p_Path)メソッドを使用する際に注意すべき点がいくつかあります。

  • 含まれるファイルの種類に制限はありませんが、インクルードされるファイルの内容はVbScriptでなければなりません。
  • インクルードされたファイルに構文エラーがある場合、エラーの行/列は取得されません。
  • IncludeFile(p_Path)最初の呼び出しの前にstd_internal_LibFiles定義して初期化する必要があります。
  • IncludeFile(p_Path)は、他のメソッドを含め、コードの任意の場所で使用できます。

「インクルードファイル」メソッドの作成

したがって、この機能の主な目的は次のとおりです。

  • 主なVBScriptファイルに書き込まれる必要があり、インクルードファイルを含めることができないため(スタンドアロンの場合)(include関数を定義しているため)
  • 何かが間違っている場合(つまり、含まれていたファイル、発生したエラーなど)に十分な情報を提供してください。
  • インクルードループを回避するには、ファイルを1回だけ含める。
' *************************************************************************************************
'! 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

ファイルを含む

別のファイルにファイルを含めるには、1つのライナーを使用します:

IncludeFile "myOtherFile.vbs"

グローバル初期化

IncludeFileメソッドを使用する前に、以下を行う必要があります。

  • std_internal_LibFilesグローバルに宣言する
  • 新しい辞書で初期化する
Dim std_internal_LibFiles
Set std_internal_LibFiles = CreateObject("Scripting.Dictionary")


Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow