我正在用VBScript编写程序来自动执行文件加密过程,并且正遇到问题。
我想根据文件比较返回的错误级别是0还是1,来测试脚本将执行哪个代码。(为简单起见,我从这篇文章中删去了该代码。)Google搜索向我指出了以下内容:为此目的,开始修改一个比较文件的过程。
Set testFile = fso.OpenTextFile(testDestFile, 8, False, 0)
但是,除非我放了,否则VBScript总是对该行抛出“找不到文件”错误
WScript.Echo "testDestFile is '" & testDestFile & "'..."
就在它前面。
我不希望这样,因为除非有必要,否则脚本的动作对用户应该是不可见的。运行该脚本时,我可以在Windows资源管理器中看到它创建了testDestFile
表示的文件。我在做什么错了?
Option Explicit
Dim baseDirLen, compareOpts, decryptOpts, destDataPath, destFolder, _
destFolderPath, encDestFile, encryptorPath, encryptOpts, file, fileName, _
folder, folderEnd, fso, keyPath, oShell, srcDataPath, srcDirEndLen, _
srcFolder, strErrorCode, testDestFile, testDiff, testFile, t
Set oShell = CreateObject("Wscript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
srcDataPath = "e:\EZcrypt\TargetData"
keyPath = "e:\EZcrypt\Key\Demo010719.key.bin"
destDataPath = "E:\EZcrypt\EncryptedData"
encryptorPath = "E:\OpenSSL-Win32\bin\openssl"
Set srcFolder = fso.GetFolder(srcDataPath)
baseDirLen = Len(srcDataPath)
recurseFolders(srcFolder)
Sub recurseFolders(srcFolder)
For Each folder In srcFolder.subfolders
srcDirEndLen = (Len(folder) - baseDirLen - 1)
folderEnd = Right(folder, srcDirEndLen)
destFolderPath = destDataPath & "\" & folderEnd & "\"
If Not fso.FolderExists(destFolderPath) Then
fso.CreateFolder(destFolderPath)
End If
For Each file In folder.Files
fileName = fso.GetFileName(file)
testDestFile = destFolderPath & "test." & fileName
encDestFile = destFolderPath & fileName & ".enc"
If Not fso.FileExists(encDestFile) Then
strErrorCode = ""
encryptOpts = encryptorPath & " enc -aes-256-cbc -salt -in """ & _
file & """ -out """ & encDestFile & _
""" -pass file:""" & keyPath & """ -pbkdf2"
oShell.Run (encryptOpts)
decryptOpts = encryptorPath & " enc -d -aes-256-cbc -in """ & _
encDestFile & """ -out """ & testDestFile & _
""" -pass file:""" & keyPath & """ -pbkdf2"
oShell.Run (decryptOpts)
WEcript.Echo "testDestFile is '" & testDestFile & "'..."
Set testFile = fso.OpenTextFile(testDestFile, 8, False, 0)
Else
WScript.Echo "'" & encDestFile & "' exists. Skipping..."
End If
Next
recurseFolders(folder)
Next
End Sub
答案 0 :(得分:3)
您观察到的行为的最可能原因是您尝试打开该文件之前运行的openssl
命令(特别是似乎正在创建该文件的加密命令)尚未完成。您无需告诉Run
方法等待命令返回,因此它们在后台异步运行。大概WScript.Echo
会添加足够的延迟,以便在代码继续打开文件之前完成加密。使用WScript.Sleep
而不是回声可能会产生相同的效果。
要解决此问题,请等待外部命令返回。
替换这些行:
encryptOpts = encryptorPath & ...
oShell.Run (encryptOpts)
decryptOpts = encryptorPath & ...
oShell.Run (decryptOpts)
与此:
encryptOpts = encryptorPath & ...
oShell.Run encryptOpts, 0, True
decryptOpts = encryptorPath & ...
oShell.Run decryptOpts, 0, True
检查外部命令的退出状态也是一种好习惯,这样您就可以查看是否出错:
rc = oShell.Run(encryptOpts, 0, True)
If rc <> 0 Then
'an error occurred
End If