1
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?

More than 3 years have passed since last update.

VBScript版Dir関数

Last updated at Posted at 2021-12-19

VBScript には、ワイルドカードでファイルの存在を検索できる Dir関数がないので、ファイル名を正規表現で検索できる VBScript版Dir関数を作ってみる。

VbsDir
'// ファイル名に正規表現の使用が可能
'//[opt:0]見つかった最初のファイル名を返す(無い場合は "" を返す)
'//[opt:1]見つかったファイル名の配列を返す
'//[opt:2]見つかったファイル名のリストを改行区切りで返す

Function VbsDir(ByVal name_pattern, ByVal opt)

    Dim regx, namesAry, fl, getNames: getNames = ""

    Set regx = CreateObject("VBScript.RegExp")

    '// 大文字・小文字を区別しない
    regx.IgnoreCase = True

    With CreateObject("Scripting.FileSystemObject")
        regx.Pattern = .GetFileName(name_pattern)
        For Each fl In .GetFolder(.GetParentFolderName(name_pattern)).Files
            If regx.Test(fl.Name) Then getNames = getNames & fl.Name & vbCrLf
        Next
    End With

	If getNames = "" Then
		namesAry = Array("")
	Else
    	namesAry = Split(getNames, vbCrLf)
    End If
    
    Select Case opt
    	Case 0
    		VbsDir = namesAry(0)
    	Case 1
    		VbsDir = namesAry
    	Case 2
    		VbsDir = getNames
    	Case Else
    		VbsDir = namesAry(0)
    End Select

End Function

テスト結果:

Dim namePattern
namePattern = "C:\Program Files\Microsoft Office\root\Office16\.*exe$"
Msgbox VbsDir(namePattern, 0)
' ⇒ ACCICONS.EXE
Msgbox VbsDir(namePattern, 2)
' ⇒ ACCICONS.EXE CLVIEW.EXE CNFNOT32.EXE EXCEL.EXE・・・
1
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
1
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?