在 VBScript 中映射网络驱动器并检查其是否存在

发布于 2024-12-03 12:58:01 字数 76 浏览 8 评论 0原文

我需要使用 VBScript 将网络驱动器映射到网络路径。网络路径直接从输入读取。如何映射网络驱动器以及如何检查输入的网络路径是否已存在?

I need to map a network drive into a network path using VBScript. The network path is read directly from input. How should I map the network drive and how to check whether the entered network path already exists?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

泪之魂 2024-12-10 12:58:01

我创建了一个子例程来映射驱动器...

    MapDrive "H:","\\server\share"

    Sub MapDrive(letter, uncpath)
         on error Resume Next
         dim drivetype, currentmapping

        dim objWMIService 
        dim colDisks, objDisk

        'Set wshnetwork = CreateObject("Wscript.Network")
        Set objWMIService = GetObject("winmgmts:" & _
             "{impersonationLevel=impersonate}!\\.\root\cimv2")
        Set colDisks = objWMIService.ExecQuery _
            ("Select * from Win32_LogicalDisk Where Name = """ & letter & """")
        For Each objDisk In colDisks        
             drivetype = objDisk.DriveType      
            currentmapping = objDisk.ProviderName
        Next    


        if (drivetype <> 4 and drivetype <> 0) then
            NotifyUser ucase(letter) & " cannot be mapped due to a physical device already reserving that drive letter" & vbcrlf & _
                        "This is most frequently caused by a thumbdrive or external disk.",5
            exit Function
        end if

        if (ucase(currentmapping) = ucase(uncpath)) then
            exit function
        end If

        if (drivemappings.Exists(uncpath)) then
            drivemappings.Add uncpath & "(" & letter & ")", letter
        else 
            drivemappings.Add uncpath, letter
        end if

        if (currentmapping <> "") then
                wshnetwork.RemoveNetworkDrive letter,,True
        end if

        wshnetwork.MapNetworkDrive letter, uncpath, true

        on Error goto 0
     End Sub

我将其留给您处理错误检查等。或者,如果您更喜欢网络使用路线,您可以执行类似的操作..

dim wshShell
Set wshShell = CreateObject("WScript.Shell")
wshshell.run "cmd /c net use H: ""\\server\share""",1,True

您可以更进一步,自动使用下一个可用的使用示例 脚本专家创建。

Set objDictionary = CreateObject("Scripting.Dictionary")

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

Set colDisks = objWMIService.ExecQuery("Select * from Win32_LogicalDisk")

For Each objDisk in colDisks
    objDictionary.Add objDisk.DeviceID, objDisk.DeviceID
Next

For i = 67 to 90
    strDrive = Chr(i) & ":"
    If objDictionary.Exists(strDrive) Then
    Else
        Wscript.Echo strDrive & " is the next available drive letter."
        Wscript.Quit
    End If
Next
Wscript.Echo "There are no available drive letters on this computer.”

我希望这有帮助。

I created a subroutine to map drives...

    MapDrive "H:","\\server\share"

    Sub MapDrive(letter, uncpath)
         on error Resume Next
         dim drivetype, currentmapping

        dim objWMIService 
        dim colDisks, objDisk

        'Set wshnetwork = CreateObject("Wscript.Network")
        Set objWMIService = GetObject("winmgmts:" & _
             "{impersonationLevel=impersonate}!\\.\root\cimv2")
        Set colDisks = objWMIService.ExecQuery _
            ("Select * from Win32_LogicalDisk Where Name = """ & letter & """")
        For Each objDisk In colDisks        
             drivetype = objDisk.DriveType      
            currentmapping = objDisk.ProviderName
        Next    


        if (drivetype <> 4 and drivetype <> 0) then
            NotifyUser ucase(letter) & " cannot be mapped due to a physical device already reserving that drive letter" & vbcrlf & _
                        "This is most frequently caused by a thumbdrive or external disk.",5
            exit Function
        end if

        if (ucase(currentmapping) = ucase(uncpath)) then
            exit function
        end If

        if (drivemappings.Exists(uncpath)) then
            drivemappings.Add uncpath & "(" & letter & ")", letter
        else 
            drivemappings.Add uncpath, letter
        end if

        if (currentmapping <> "") then
                wshnetwork.RemoveNetworkDrive letter,,True
        end if

        wshnetwork.MapNetworkDrive letter, uncpath, true

        on Error goto 0
     End Sub

I leave it up to you do handle error checking etc. Alternatively if you prefer the net use route you could do something like..

dim wshShell
Set wshShell = CreateObject("WScript.Shell")
wshshell.run "cmd /c net use H: ""\\server\share""",1,True

You can take it a step further to automagically use the next available drive letter to map drives using an example The Scripting Guys created.

Set objDictionary = CreateObject("Scripting.Dictionary")

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

Set colDisks = objWMIService.ExecQuery("Select * from Win32_LogicalDisk")

For Each objDisk in colDisks
    objDictionary.Add objDisk.DeviceID, objDisk.DeviceID
Next

For i = 67 to 90
    strDrive = Chr(i) & ":"
    If objDictionary.Exists(strDrive) Then
    Else
        Wscript.Echo strDrive & " is the next available drive letter."
        Wscript.Quit
    End If
Next
Wscript.Echo "There are no available drive letters on this computer.”

I hope this is helpful.

平定天下 2024-12-10 12:58:01

在 vbscript 文件中运行以下命令:

net use [NetDrive:] [Network Path]

例如:

net use Z: \\Hadi\temp

示例命令会将 \Hadi\temp 映射到 Z:

另请参阅 此 VBScript 文件用于映射网络驱动器。

run the following command in you vbscript file:

net use [NetDrive:] [Network Path]

for example:

net use Z: \\Hadi\temp

The sample command will map \Hadi\temp to Z:

Also take a look at this VBScript file for mapping network drives.

最近可好 2024-12-10 12:58:01

我本人并不是 WMI 的忠实粉丝(它有点臃肿且缓慢),因此我使用以下代码将网络共享映射到第一个可用的驱动器号,并检查它是否已成功安装:

Dim strScriptPath, strMapNetworkDriveLetter
strScriptPath = Left(WScript.ScriptFullName, Len(WScript.ScriptFullName) - Len(WScript.ScriptName)-1) 
strMapNetworkDriveLetter = GetFirstFreeDriveLetter & "\"

Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject")

strScriptPath = RemoveTrailingBackslash(strScriptPath)

If Left(strScriptPath, 2) = "\\" Then
    ' Create Drive Mapping
    Dim WshNetwork
    Set WshNetwork = WScript.CreateObject("WScript.Network")

    WshNetwork.MapNetworkDrive RemoveTrailingBackslash(strMapNetworkDriveLetter), strScriptPath
    If objFSO.DriveExists(strMapNetworkDriveLetter) Then
        Dim objDrives, boolMapNetworkDrive, i
        Set objDrives = WshNetwork.EnumNetworkDrives
        boolMapNetworkDrive = False
        For i = 0 to objDrives.Count - 1 Step 2
            WScript.Echo "[debug] " & objDrives.Item(i) & " = " & objDrives.Item(i+1)
            If objDrives.Item(i) = RemoveTrailingBackslash(strMapNetworkDriveLetter) Then
                If objDrives.Item(i+1) = strScriptPath Then
                    WScript.Echo "[debug] Drive " & objDrives.Item(i) & " is now connected to " & objDrives.Item(i+1) & vbCrLf
                    boolMapNetworkDrive = True
                    Exit For
                End If
            End If
        Next
    End If
    
    If Not boolMapNetworkDrive Then
        ShowMessage("The network connection (" & strScriptPath & ") could not be found.")
        WScript.Quit(2)
    End If
End If

' Do your stuff here...

' Unmount UNC Drive Mapping after script execution.
If boolMapNetworkDrive Then
    WScript.Echo("WshNetwork.RemoveNetworkDrive " & RemoveTrailingBackslash(strMapNetworkDriveLetter))
    WshNetwork.RemoveNetworkDrive RemoveTrailingBackslash(strMapNetworkDriveLetter), True
    If objFSO.DriveExists(strMapNetworkDriveLetter) Then
        WScript.Echo("Error on WshNetwork.RemoveNetworkDrive.")
        WScript.Quit(3)
    End If
End If

Function GetFirstFreeDriveLetter
 
    Dim objFSO, strLetters, i,  blnError 
    Set objFSO = CreateObject("Scripting.FileSystemObject") 
     
    '* list of possible drive letters 
    '* A and B are reserved for floppy disc 
    '* you may limit the search using any subset of the alphabet 
    strLetters = "CDEFGHIJKLMNOPQRSTUVWXYZ"  
    GetFirstFreeDriveLetter = "" 
    blnError = True 
     
    '* walk through all possible drive letters 
    For i=1 to len(strLetters) 
    '* if the drive letter isn't in use the it's ours 
        If not objFSO.DriveExists(mid(strLetters, i, 1) & ":") Then 
            '* we have found a free drive letter, therefore blnError = False 
            blnError = False 
            '* assigning the return value 
            GetFirstFreeDriveLetter = mid(strLetters, i, 1) & ":" 
            '* we want to find the FIRST free drive letter 
            Exit For 
        End If 
    Next  
     
    '* error handling 
    If blnError then  
        WScript.Echo "Error - no free drive letter found!"  
        WScript.Quit(1)
    End If 
     
    '* releasing file system object 
    Set objFSO = Nothing 
 
End Function 

Function RemoveTrailingBackslash(strString)
    If Right(strString, 1) = "\" Then
        RemoveTrailingBackslash = Left(strString, Len(strString)-1)
    Else
        RemoveTrailingBackslash = strString
    End If
End Function

I am not a big fan o WMI by myself (it's a little bloat and slow), so I used the following code to map a network share to the first available drive letter and checks if it was mounted successfully:

Dim strScriptPath, strMapNetworkDriveLetter
strScriptPath = Left(WScript.ScriptFullName, Len(WScript.ScriptFullName) - Len(WScript.ScriptName)-1) 
strMapNetworkDriveLetter = GetFirstFreeDriveLetter & "\"

Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject")

strScriptPath = RemoveTrailingBackslash(strScriptPath)

If Left(strScriptPath, 2) = "\\" Then
    ' Create Drive Mapping
    Dim WshNetwork
    Set WshNetwork = WScript.CreateObject("WScript.Network")

    WshNetwork.MapNetworkDrive RemoveTrailingBackslash(strMapNetworkDriveLetter), strScriptPath
    If objFSO.DriveExists(strMapNetworkDriveLetter) Then
        Dim objDrives, boolMapNetworkDrive, i
        Set objDrives = WshNetwork.EnumNetworkDrives
        boolMapNetworkDrive = False
        For i = 0 to objDrives.Count - 1 Step 2
            WScript.Echo "[debug] " & objDrives.Item(i) & " = " & objDrives.Item(i+1)
            If objDrives.Item(i) = RemoveTrailingBackslash(strMapNetworkDriveLetter) Then
                If objDrives.Item(i+1) = strScriptPath Then
                    WScript.Echo "[debug] Drive " & objDrives.Item(i) & " is now connected to " & objDrives.Item(i+1) & vbCrLf
                    boolMapNetworkDrive = True
                    Exit For
                End If
            End If
        Next
    End If
    
    If Not boolMapNetworkDrive Then
        ShowMessage("The network connection (" & strScriptPath & ") could not be found.")
        WScript.Quit(2)
    End If
End If

' Do your stuff here...

' Unmount UNC Drive Mapping after script execution.
If boolMapNetworkDrive Then
    WScript.Echo("WshNetwork.RemoveNetworkDrive " & RemoveTrailingBackslash(strMapNetworkDriveLetter))
    WshNetwork.RemoveNetworkDrive RemoveTrailingBackslash(strMapNetworkDriveLetter), True
    If objFSO.DriveExists(strMapNetworkDriveLetter) Then
        WScript.Echo("Error on WshNetwork.RemoveNetworkDrive.")
        WScript.Quit(3)
    End If
End If

Function GetFirstFreeDriveLetter
 
    Dim objFSO, strLetters, i,  blnError 
    Set objFSO = CreateObject("Scripting.FileSystemObject") 
     
    '* list of possible drive letters 
    '* A and B are reserved for floppy disc 
    '* you may limit the search using any subset of the alphabet 
    strLetters = "CDEFGHIJKLMNOPQRSTUVWXYZ"  
    GetFirstFreeDriveLetter = "" 
    blnError = True 
     
    '* walk through all possible drive letters 
    For i=1 to len(strLetters) 
    '* if the drive letter isn't in use the it's ours 
        If not objFSO.DriveExists(mid(strLetters, i, 1) & ":") Then 
            '* we have found a free drive letter, therefore blnError = False 
            blnError = False 
            '* assigning the return value 
            GetFirstFreeDriveLetter = mid(strLetters, i, 1) & ":" 
            '* we want to find the FIRST free drive letter 
            Exit For 
        End If 
    Next  
     
    '* error handling 
    If blnError then  
        WScript.Echo "Error - no free drive letter found!"  
        WScript.Quit(1)
    End If 
     
    '* releasing file system object 
    Set objFSO = Nothing 
 
End Function 

Function RemoveTrailingBackslash(strString)
    If Right(strString, 1) = "\" Then
        RemoveTrailingBackslash = Left(strString, Len(strString)-1)
    Else
        RemoveTrailingBackslash = strString
    End If
End Function
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文