我正在尝试开发一个将文件复制到特定驱动器的简单脚本。
脚本执行以下操作:
当存在网络驱动器或通过脚本创建网络映射驱动器时,XCopy命令可以正常工作。 问题出在第1步,并且本地驱动器已经存在,调用XCopy后没有文件复制到驱动器。
这是我的代码:
strLocalDrive = "E:"
strRemoteShare = "\\127.0.0.1\c$\Program Files (x86)\MyFolder\EDrive"
bolFoundExisting = False
source = "C:\Program Files (x86)\MyFolder\EDrive\*"
destination = "E:\"
' Check parameters passed make sense
If Right(strLocalDrive, 1) <> ":" OR Left(strRemoteShare, 2) <> "\\" Then
'wscript.echo "Usage: cscript MapDrive.vbs drive fileshare //NoLogo"
WScript.Quit(1)
End If
'wscript.echo " - Mapping: " + strLocalDrive + " to " + strRemoteShare
'Set objNetwork = WScript.CreateObject("WScript.Network")
Set objNetwork = CreateObject("WScript.Network")
Set oShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Loop through the network drive connections and disconnect any that match strLocalDrive
Set objDrives = objNetwork.EnumNetworkDrives
' first check that physical drive does not exist
If objFSO.DriveExists(strLocalDrive) Then
WScript.echo "Physical Drive Found"
bolFoundExisting = True
ElseIf objDrives.Count > 0 Then
For i = 0 To objDrives.Count-1 Step 2
If objDrives.Item(i) = strLocalDrive Then
strShareConnected = objDrives.Item(i+1)
'objNetwork.RemoveNetworkDrive strLocalDrive, True, True
i=objDrives.Count-1
bolFoundExisting = True
End If
Next
End If
If bolFoundExisting <> True Then
WScript.echo "Drive DOES NOT exists"
Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
objReg.GetStringValue HKCU, "Network\" & Left(strLocalDrive, 1), "RemotePath", strShareConnected
If strShareConnected <> "" Then
Set objReg = Nothing
bolFoundRemembered = True
End If
'Now actually do the drive map (not persistent)
Err.Clear
On Error Resume Next
objNetwork.MapNetworkDrive strLocalDrive, strRemoteShare, False
Else
' Drive exists copy files
WScript.echo "Drive exists"
oShell.Run "xcopy.exe " & source & " " & destination & " /C /D /E /H /I /K /R /S /Y"
Set oShell = Nothing
End IF
如果有人可以解释为什么XCOPY命令只将文件复制到网络驱动器而不是本地驱动器,我真的很感激! TIA!
更新 我已经意识到问题是由路径名中的空格引起的。 奇怪的是,复制到网络驱动器确实有效,但不能用于物理驱动器。 如何处理路径名中的空格?
答案 0 :(得分:1)
您的路径中有空格,无法在运行xcopy
命令时扩展。与您需要在命令行上使用引号的方式相同,您需要引用.Run
的字符串。插入双引号的首选方法是使用Chr(34)
。 34是双引号的ANSI代码
一个简单的例子是chr(34) & "quotedstring" & chr(34)
。对于你的情况,你可以使用这样的东西:
oShell.Run "xcopy.exe " & chr(34) & source & chr(34) & " " & chr(34) & destination & chr(34) & " /C /D /E /H /I /K /R /S /Y"
对于可读性,您始终可以使用下划线来划分界限
oShell.Run "xcopy.exe " & chr(34) & source & chr(34) & " " & _
chr(34) & destination & chr(34) & _
" /C /D /E /H /I /K /R /S /Y"