0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SQLファイル編集ようVBSサンプル

Posted at

Option Explicit

Const FOLDER_PATH = "C:\a"
Const STRING_TO_REMOVE = "AAA" ' 削除する特定の文字列
Const CUTOFF_STRING = "BBB" ' この文字列以降を削除

Dim fso, folder, file, content, newContent, filesProcessed
Set fso = CreateObject("Scripting.FileSystemObject")

' フォルダが存在するか確認
If Not fso.FolderExists(FOLDER_PATH) Then
WScript.Echo "指定されたフォルダが存在しません: " & FOLDER_PATH
WScript.Quit 1
End If

Set folder = fso.GetFolder(FOLDER_PATH)
filesProcessed = 0

' SQLファイルを処理
For Each file In folder.Files
If LCase(fso.GetExtensionName(file.Name)) = "sql" Then
' ファイルの内容を読み込む
content = ReadFile(file.Path)

    ' 特定の文字列を削除
    newContent = Replace(content, STRING_TO_REMOVE, "")
    
    ' CUTOFF_STRING以降の記述を削除
    Dim pos
    pos = InStr(1, newContent, CUTOFF_STRING, vbTextCompare)
    If pos > 0 Then
        newContent = Left(newContent, pos - 1)
    End If
    
    ' 内容が変更された場合のみファイルを更新
    If StrComp(content, newContent, vbBinaryCompare) <> 0 Then
        WriteFile file.Path, newContent
        filesProcessed = filesProcessed + 1
        WScript.Echo "処理済み: " & file.Name
    End If
End If

Next

WScript.Echo filesProcessed & " 個のSQLファイルの処理が完了しました。"

' ファイルの内容を読み込む関数
Function ReadFile(filePath)
Dim objFile, content
On Error Resume Next
Set objFile = fso.OpenTextFile(filePath, 1)
If Err.Number <> 0 Then
WScript.Echo "エラー: ファイルを読み込めません - " & filePath
WScript.Quit 1
End If
On Error Goto 0

content = objFile.ReadAll
objFile.Close
ReadFile = content

End Function

' ファイルに内容を書き込む関数
Sub WriteFile(filePath, content)
Dim objFile
On Error Resume Next
Set objFile = fso.OpenTextFile(filePath, 2, True)
If Err.Number <> 0 Then
WScript.Echo "エラー: ファイルに書き込めません - " & filePath
WScript.Quit 1
End If
On Error Goto 0

objFile.Write content
objFile.Close

End Sub

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?