vbscript选择文件并保存目录?

时间:2015-07-27 14:41:36

标签: batch-file vbscript

我目前正在开发一个可以启动其他程序的程序。它是批量的。但我需要它是用户友好的。我想要一个可以打开文件选择窗口的代码,并将我选择的目录保存到txt文件(或csv或其他)中。我是VBS的新人,请原谅我,如果我错过了一些简单的事情。但是我搜索了一会儿并且接近了,只是失败了。

这是我到目前为止所拥有的......

Set shell = CreateObject( "WScript.Shell" )

defaultLocalDir = shell.ExpandEnvironmentStrings("%USERPROFILE%") & "\Desktop"
Set shell = Nothing

file = ChooseFile(defaultLocalDir)


wscript.echo file


Function ChooseFile (ByVal initialDir)
    Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")

    Set colItems = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")
    Dim winVersion

    ' This collection should contain just the one item
    For Each objItem in colItems
        'Caption e.g. Microsoft Windows 7 Professional
        'Name e.g. Microsoft Windows 7 Professional |C:\windows|...
        'OSType e.g. 18 / OSArchitecture e.g 64-bit
        'Version e.g 6.1.7601 / BuildNumber e.g 7601
        winVersion = CInt(Left(objItem.version, 1))
    Next
    Set objWMIService = Nothing
    Set colItems = Nothing

    If (winVersion <= 5) Then
        ' Then we are running XP and can use the original mechanism
        Set cd = CreateObject("UserAccounts.CommonDialog")
        cd.InitialDir = initialDir
        cd.Filter = "ZIP files|*.zip|Text Documents|*.txt|Shell Scripts|*.*sh|All Files|*.*"
        ' filter index 4 would show all files by default
        ' filter index 1 would show zip files by default
        cd.FilterIndex = 1
        If cd.ShowOpen = True Then
            ChooseFile = cd.FileName
        Else
            ChooseFile = ""
        End If
        Set cd = Nothing    

    Else
        ' We are running Windows 7 or later
        Set shell = CreateObject( "WScript.Shell" )
        Set ex = shell.Exec( "mshta.exe ""about: <input type=file id=X><script>X.click();new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).WriteLine(X.value);close();resizeTo(0,0);</script>""" )
        ChooseFile = Replace( ex.StdOut.ReadAll, vbCRLF, "" )

        Set ex = Nothing
        Set shell = Nothing
    End If
End Function    

1 个答案:

答案 0 :(得分:0)

也许您正在寻找类似下一个bat代码段的内容?

@echo OFF
SETLOCAL enableextensions
set "_chosen="
if exist "_saved.txt" (
   rem read previously saved value
   <"_saved.txt" set /P "_chosen="
   echo read previously saved value
) else (
  for /f "delims=" %%G in ('
       cscript //NOLOGO "D:\VB_scripts\SO\31656148.vbs"
    ') do (
      set "_chosen=%%G"
      rem save value to a file
      >"_saved.txt" echo(%%G
      echo file chosen, value saved
  )
)
if defined _chosen (
    echo("%_chosen%"
) else (
    echo no file chosen
)