首页 > 解决方案 > Do I need to use WMI in order to merge text files in VBScript?

问题描述

while searching for hints about merging text files in VBScript, I came accross this example: https://gallery.technet.microsoft.com/scriptcenter/Merge-multiple-txt-files-cbe9625c

Const ForReading = 1 

Set objFSO = CreateObject("Scripting.FileSystemObject") 
Set objOutputFile = objFSO.CreateTextFile("output.txt") 

strComputer = "." 
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") 

Set FileList = objWMIService.ExecQuery _ 
    ("ASSOCIATORS OF {Win32_Directory.Name='z:\Scripts\Test'} Where " _ 
        & "ResultClass = CIM_DataFile") 

For Each objFile In FileList 
    Set objTextFile = objFSO.OpenTextFile(objFile.Name, ForReading)  
    strText = objTextFile.ReadAll 
    objTextFile.Close 
    objOutputFile.WriteLine strText 
Next 

objOutputFile.Close

Instructions are just as follow:

You can merge multiple txt files from specific folder to one txt file. It will merge all data to one txt file. You dont need to copy data manually. You can execute this script directly or from command promt. In this script you need to change the folder path from z:\Scripts\Test to your existing path where all txt files are available as well as change the name "output.txt" with your require output file name and path.

Although I'm quite new at VBScript (and didn't write VBScript for a very very long time), I don't get the point of using this WMI service for such a simple task (i.e. handling files in the same folder).

Wouldn't it be enough to just use folder.Files then filter the files to your need?

Thanks for your help.

标签: mergevbscriptwmi

解决方案


You are absolutely right, using WMI for this task is silly.

This will do just fine, and it will be a lot faster, too:

Option Explicit

Dim FSO, OutputFile, File

Set FSO = CreateObject("Scripting.FileSystemObject")
Set OutputFile = FSO.CreateTextFile("output.txt")

For Each File In FSO.GetFolder("Z:\Scripts\Test").Files
    If LCase(FSO.GetExtensionName(File.Name)) = "txt" Then
        With FSO.OpenTextFile(File.Path)
            OutputFile.WriteLine .ReadAll
            .Close
        End With
    End If
Next

OutputFile.Close

推荐阅读