How to unzip a password-protected file in vbscript? - vbscript

I am fairly new to VBScript. I have done some extensive research on what I am trying to accomplish and have even found examples of what to do, but cannot get it to work properly.
In my perfect world, I need to unzip all zipped files sent to a folder from a third-party vendor, import the unzipped file into a different folder then delete the zipped file.
The script below works properly for non-password protected zip files, but all files sent from the vendor have passwords. As seen in another post, the following lines which I have commented out should insert the password but do not. "...(pwd+myZipfile)" and "...(pwd+extractTo)".
Thank you in advanced for your help. Please suggest any code improvements or other methods to make this happen.
pathToZipFile = "P:\ZipFiles"
extractTo = "P:\UnZip"
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFolder(pathToZipFile)
Set fc = f.Files
Dim myZipFile
Dim intOptions, objShell, objSource, objTarget
Dim pwd
pwd = "password"
For Each f1 in fc
On Error Resume Next
myZipFile = f1
' Create the required Shell objects
Set objShell = CreateObject( "Shell.Application" )
' Create a reference to the files and folders
'Set objSource = objShell.NameSpace(pwd+myZipFile).Items( )
Set objSource = objShell.NameSpace(myZipFile).Items( )
' Create a reference to the target folder
Set objTarget = objShell.NameSpace(pwd+extractTo)
Set objTarget = objShell.NameSpace(extractTo)
intOptions = 256
' UnZIP the file
objTarget.CopyHere objSource, intOptions
' Release the objects
Set objSource = Nothing
Set objTarget = Nothing
Set objShell = Nothing
'Delete File from "P:\ZipFiles" after unzipping
fso.DeleteFile f1, True
Next

If you take a closer look at the answer from which the pwd+... came, you'll notice that pwd does not contain a password, but a path. The variable was probably named after the Unix command pwd, which stands for "print working directory".
As far as I know the Shell.Application object does not support unpacking password-protected Zip files. Another answer to the question you referenced suggests the DotNetZip library. Or you could use 7-zip:
Function qq(str)
qq = Chr(34) & str & Chr(34)
End Function
zipfile = "..."
password = "..."
Set sh = CreateObject("WScript.Shell")
sh.Run "7za.exe x " & qq(zipfile) & " -p" & qq(password), 0, True

Related

Cant move VBScript to another directory, it says "File not found"

Set objShell = CreateObject("Wscript.Shell")
strFile ="Lafarrel.vbs"
dim fso, fullPath
set fso = CreateObject("Scripting.FileSystemObject")
fullPath = fso.GetAbsolutePathName(strFile)
Wscript.Echo fullPath
Wscript.Sleep 1000
dim SourceLocation
dim DestinationLocation
dim FileName
SourceLocation = fullPath
DestinationLocation = """C:\Users\%username%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\"""
FileName = "Lafarrel.vbs"
fso.MoveFile SourceLocation & "" & FileName, DestinationLocation & ""
Error starts at line 14
Maybe because the last line is incorrect?
Explain what I want VBScript to do:
I want this VBScript to find itself and then change to a different directory
Use Option Explicit, for everyones' sanity.
Wscript.Sleep 1000 is unnecessary.
This line has problems: DestinationLocation = """C:\Users\%username%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\"""
This string-literal contains excessive double-quotes (VBScript uses double-double-quotes to escape individual double-quote chars, but strings containing only paths and filenames should not have internal delimiting quotes.
Also, %username% won't be expanded by FileSystemObject.MoveFile.
You will need to use WshShell.ExpandEnvironmentStrings first.
Also, C:\Users\%username%\AppData\Roaming\... is a poor choice of environment-variable'd-path as the Users directory might not be on C:\, and it might not even be named "Users".
Instead, you should use %APPDATA%.
obj prefixes are ugly and unnecessary.
Dim SourceLocation is redundant as it's an alias of fullPath. Ditto Dim FileName.
GetAbsolutePathName does not verify that the file actually exists: you'll get a runtime error if "Lafarrel.vbs" does not exist in the expected location when the script runs - so expect this situation and add an If guard.
So your code should look like this:
Option Explicit
Dim shell
Set shell = CreateObject( "WScript.Shell" ) ' aka WshShell
Dim fso
Set fso = CreateObject( "Scripting.FileSystemObject" )
Dim lafarrelVbsPath
lafarrelVbsPath = fso.GetAbsolutePathName( "Lafarrel.vbs" )
If fso.FileExists( lafarrelVbsPath ) Then
Dim destinationPath
destinationPath = "%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup\"
destinationPath = shell.ExpandEnvironmentStrings( destinationPath )
Wscript.Echo "Moving """ & lafarrelVbsPath & """ to """ & destinationPath & """..."
' When `destinationPath` ends with a slash, then "Lafarrel.vbs" won't be renamed (phew).
fso.MoveFile lafarrelVbsPath, destinationPath
Else
Wscript.Echo "Error: File not found: """ & lafarrelVbsPath & """."
End If
WScript.ScriptFullName returns the script path and filename in full.
This sample demonstrates a couple of things including a simple way to isolate the script folder (not really needed for your use case though).
If you save this exact script into your local %temp% folder, and create a folder '%temp%\temp two' (space in there) you can just run it.
Also you MUST use ExpandEnvironmentStrings method to use env vars in a string
strFileName = WScript.Scriptname
strCurrDir = Replace(WScript.ScriptFullName, WScript.Scriptname, "")
Set wshShell = CreateObject("WScript.Shell")
strDestination = wshShell.ExpandEnvironmentStrings("%temp%\temp two\") ' note the space, but no need to double-up quotes. You MUST use ExpandEnvironmentStrings method to use env vars in a string
Wscript.Echo "I am '" & strFileName & "' and I am in '" & strCurrDir & "'"
WScript.Echo "My full path and name in one is: " & WScript.ScriptFullName
' so for moving the file, no need to separate the path and filename, as 'WScript.ScriptFullName' contains all of it (dest file must NOT exist)
' no need to double-up quotes for destination path, as this is not batch and will treat the whole string as path including spaces
Set fso = CreateObject("Scripting.FileSystemObject")
fso.MoveFile WScript.ScriptFullName, strDestination
WScript.Echo "I've now been moved to: " & strDestination

How to Copy a file that was read from a list

Hello guys I have an issue or issues with my code above
I'm trying to get "sExtension" to be search in a different folder other that the one I'm using to save my script since this script will be use as a Startup Script on many computers
(It works only if I run the script in the same folder "sExtension", "ExtAssign.txt" and sComputername are otherwise it wont find the path)
This is what it should do
Read a file called "ExtAssign.txt" (There is a full list of computer names in that file) and if it find the computer name on that file then it should copy a file with the with the extension number assigned to that computer name from a file server to "C:\" Drive
For this example I'm trying to do this locally, If I can make it then I'll try it from my File Server
Set objFSO = CreateObject("Scripting.FileSystemObject")
set oFso = CreateObject("Scripting.FileSystemObject")
Set objFS = CreateObject("Scripting.FileSystemObject")
Set fso = CreateObject("Scripting.FileSystemObject")
set oShell = WScript.CreateObject("WScript.Shell")
set oShellEnv = oShell.Environment("Process")
Set folder = Fso.GetFolder("C:\Users\XXXXX\Desktop\Test\Extensions\")
Set wshshell = CreateObject("WScript.Shell")
Set objNetwork = CreateObject("WScript.Network")
Set ObjEnv = WshShell.Environment("Process")
Set objFso = WScript.CreateObject("Scripting.FileSystemObject")
Scomputername = ObjEnv("COMPUTERNAME")
Set objFSO = CreateObject("Scripting.FileSystemObject")
set objWShell = wScript.createObject("WScript.Shell")
Dim strFile
'File to scan
strFile = "C:\Users\XXXXX\Desktop\Test\Extensions\Extassign\ExtAssign.txt"
Dim strPattern
'Look for computer name in file
strPattern = scomputername
Set objFso = WScript.CreateObject("Scripting.FileSystemObject")
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
Dim strLine
'Read each line and store it in strLine
strLine = objFile.ReadLine
'If the line matches the computer name, save the line to ExtArray
If InStr(strLine,strPattern)>0 Then
Dim ExtArray
'Split the line and separate the extension
ExtArray = Split(strLine,"|", -1, 1)
Dim sExtension
'Save the extension to sExtension
sExtension=ExtArray(1)
End If
Loop
'If the sExtension is empty, computer was not found, send message and terminate script.
If sExtension="" Then
WScript.Echo "ERROR: Computer "& scomputername &" not found in Extension Assignment List, so no extension has been set. Avaya will not be launched. Please contact your IT department for assistance."
Else
'If the sExtension contains a number, Copy that file to C:\ and rename it to Config.xml
fso.CopyFile "C:\Users\XXXXX\Desktop\Test\Extensions\ "& sExtension &"", "C:\Config.xml", True
End If
at the end it if it finds the file sExtension it will rename it to Config.xml but it wont do it unless I run the script in the same folder sExtension and sComputername.
I get File not found error
Thank you in advance and Happy new year!
The culprit is most likely this line:
fso.CopyFile "C:\Users\XXXXX\Desktop\Test\Extensions\ "& sExtension &"", "C:\Config.xml", True
There is a trailing space after the last backslash in the path, so you're creating a path
C:\Users\XXXXX\Desktop\Test\Extensions\ 12345
^
when you actually want a path
C:\Users\XXXXX\Desktop\Test\Extensions\12345
On a more general note: why are you creating 7(!) FileSystemObject instances (replacing one of them three times on top of that)? And 3(!) WScript.Shell instances? You don't even use most of them, not to mention that you don't need the Shell object in the first place. You only use it for determining the computer name, which could be done just fine using the WScript.Network object (that you don't use at all).
Also, please don't ever use comments like this:
'Read each line and store it in strLine
strLine = objFile.ReadLine
It's quite obvious that you read each line and assign it to the variable strLine. Comments shouldn't rephrase what you're doing (the code already does that, at least when you're using speaking variable and function names), but why you're doing it, i.e. what the purpose of a particular code section is.
Your code could be reduced to something as simple as this:
Set fso = CreateObject("Scripting.FileSystemObject")
Set net = CreateObject("WScript.Network")
computername = net.ComputerName
foldername = "C:\Users\XXXXX\Desktop\Test\Extensions"
filename = fso.BuildPath(foldername, "Extassign\ExtAssign.txt")
Set f = fso.OpenTextFile(filename)
Do Until f.AtEndOfStream
line = f.ReadLine
If InStr(line, computername) > 0 Then
arr = Split(line, "|", -1, 1)
If UBound(arr) >= 1 Then extension = arr(1)
End If
Loop
f.Close
If IsEmpty(extension) Then
WScript.Echo "ERROR: Computer "& computername &" not found in ..."
Else
fso.CopyFile fso.BuildPath(foldername, extension), "C:\Config.xml", True
End If

Creating a Zip then copying folders to it

I'm trying to create a zip file, then copy three folders into it. I get the error on line 33 char 1, error state object required, I have searched and googled but just can't seem to either understand what I'm reading or understand what I really need to search for. Anyhow, here is my code.
Option Explicit
Dim objFSO, objFolder1, objFolder2, objFolder3, FolderToZip, ziptoFile, FolderGroup
Dim ShellApp, eFile, oNewZip, strZipHeader
Dim ZipName, Folder, i, Zip, Item
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder1 = objFSO.GetFolder("C:\Windows\Temp\SMSTSLog")
Set objFolder2 = objFSO.GetFolder ("C:\Windows\System32\CCM\Logs")
Set objFolder3 = objFSO.GetFolder ("C:\Windows\SysWOW64\CCM\Logs")
'For Each efile In objFolder.Files
' If DateDiff("d",eFile.DateLastModified,Now) >= 2 Then
' objFSO.MoveFile eFile, "C:\Documents and Settings\User\Desktop\Test2\"
' End If
'Next
Wscript.Sleep 2000
Set oNewZip = objFSO.OpenTextFile("C:\win7tools\testing script.zip", 8, True)
strZipHeader = "PK" & Chr(5) & Chr(6)
For i = 0 To 17
strZipHeader = strZipHeader & Chr(0)
Next
oNewZip.Write strZipHeader
oNewZip.Close
Set oNewZip = Nothing
WScript.Sleep 5000
FolderGroup = Array(objFolder1,objFolder2,objFolder3)
FolderToZip = "FolderGroup"
ZipToFile = "C:\Win7tools\Test Script.zip"
Set ShellApp = CreateObject("Shell.Application")
Set Zip = ShellApp.NameSpace(ZipToFile)
'Set Folder = ShellApp.NameSpace(FolderToZip)
ShellApp.NameSpace(FolderGroup).CopyHere Zip.NameSpace(ZipToFile)
WScript.Sleep 10000
set ShellApp = Nothing
set FolderToZip = Nothing
set ZipToFile = Nothing
When in doubt, read the documentation:
retVal = Shell.NameSpace(
vDir
)
Parameters
vDir [in]
Type: Variant
The folder for which to create the Folder object. This can be a string that specifies the path of the folder or one of the ShellSpecialFolderConstants values. Note that the constant names found in ShellSpecialFolderConstants are available in Visual Basic, but not in VBScript or JScript. In those cases, the numeric values must be used in their place.
The NameSpace method expects either a string with a path or the integer value of one of the ShellSpecialFolderConstants, not an array of Folder objects. Also you got the order wrong. The object on which you call the copyHere method is the zip file. The argument is what you want to copy to the zip file (a path string should do just fine here). Plus, the name of the zip file you create is different from the name of the zip file you try to add the folders to.
Change your code to this:
folder1 = "C:\Windows\Temp\SMSTSLog"
folder2 = "C:\Windows\System32\CCM\Logs"
folder3 = "C:\Windows\SysWOW64\CCM\Logs"
zipfile = "C:\Win7tools\Test Script.zip"
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.OpenTextFile(zipfile, 2, True).Write "PK" & Chr(5) & Chr(6) _
& String(18, Chr(0))
Set ShellApp = CreateObject("Shell.Application")
Set zip = ShellApp.NameSpace(zipfile)
zip.CopyHere folder1
zip.CopyHere folder2
zip.CopyHere folder3
WScript.Sleep 10000
WinZip has a Command Line Interface. You might have to download and install it depending on your version: http://www.winzip.com/prodpagecl.htm
The below is a test script that works for WinZip version 9.0 if it helps.
Const WinZip = "C:\Program Files\WinZip9.0\wzzip.exe" 'WinZip Version 9.0
BasePath = "C:\Path\To\Folders\"
strZipFilePath = BasePath & "Test.zip"
strArchiveMe = BasePath & "Folder_A"
Set objShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FileExists(WinZip) Then
MsgBox "WinZip (wzzip.exe) Does Not Exist"
WScript.Quit
End If
'''// For Below Command - Change "-a" TO "-mu" To Auto Delete The file After Zip Is Created
'''// For Below Command - Change "-yb" TO "-ybc" To Answer YES To all Promps and not Terminate Operation
strcommand = Chr(34) & WinZip & Chr(34) & " -a -yb " & Chr(34) & strZipFilePath & Chr(34) & " " & Chr(34) & strArchiveMe & Chr(34)
objShell.Run strcommand, 1, True
The command format is:
winzip [action] [options] [Zip Path] [Path to file/folder to zip]

Getting current directory in VBScript

I'm trying to get the current directory and use it to run an application no matter where the file is put and no matter how the path is changed
Dim fso: set fso = CreateObject("Scripting.FileSystemObject")
Dim CurrentDirectory
CurrentDirectory = fso.GetAbsolutePathName(".")
Dim Directory
Directory = CurrentDirectory\attribute.exe
Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run Chr(34) & "Directory" & Chr(34), 0
Set WinScriptHost = Nothing
How do I actually set up this code so it does what I want it to do correctly?
You can use WScript.ScriptFullName which will return the full path of the executing script.
You can then use string manipulation (jscript example) :
scriptdir = WScript.ScriptFullName.substring(0,WScript.ScriptFullName.lastIndexOf(WScript.ScriptName)-1)
Or get help from FileSystemObject, (vbscript example) :
scriptdir = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)
You can use CurrentDirectory property.
Dim WshShell, strCurDir
Set WshShell = CreateObject("WScript.Shell")
strCurDir = WshShell.CurrentDirectory
WshShell.Run strCurDir & "\attribute.exe", 0
Set WshShell = Nothing
Your problem is not getting the directory (fso.GetAbsolutePathName(".") resolves the current working directory just fine). Even if you wanted the script directory instead of the current working directory, you could easily determine that as Jakob Sternberg described in his answer.
What does not work in your code is building a path from the directory and your executable. This is invalid syntax:
Directory = CurrentDirectory\attribute.exe
If you want to build a path from a variable and a file name, the file name must be specified as a string (or a variable containing a string) and either concatenated with the variable directory variable:
Directory = CurrentDirectory & "\attribute.exe"
or (better) you construct the path using the BuildPath method:
Directory = fso.BuildPath(CurrentDirectory, "attribute.exe")
'-----Implementation of VB6 App object in VBScript-----
Class clsApplication
Property Get Path()
Dim sTmp
If IsObject(Server) Then
'Classic ASP
Path = Server.MapPath("../")
ElseIf IsObject(WScript) Then
'Windows Scripting Host
Path = Left(WScript.ScriptFullName, InStr(WScript.ScriptFullName, WScript.ScriptName) - 2)
ElseIf IsObject(window) Then
'Internet Explorer HTML Application (HTA)
sTmp = Replace( Replace(Unescape(window.location), "file:///", "") ,"/", "\")
Path = Left(sTmp, InstrRev( sTmp , "\") - 1)
End If
End Property
End Class
Dim App : Set App = New clsApplication 'use as App.Path
Your line
Directory = CurrentDirectory\attribute.exe
does not match any feature I have encountered in a vbscript instruction manual.
The following works for me, tho not sure what/where you expect "attribute.exe" to reside.
dim fso
dim curDir
dim WinScriptHost
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing
Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run curDir & "\testme.bat", 1
set WinScriptHost = nothing
Use With in the code.
Try this way :
''''Way 1
currentdir=Left(WScript.ScriptFullName,InStrRev(WScript.ScriptFullName,"\"))
''''Way 2
With CreateObject("WScript.Shell")
CurrentPath=.CurrentDirectory
End With
''''Way 3
With WSH
CD=Replace(.ScriptFullName,.ScriptName,"")
End With
simple:
scriptdir = replace(WScript.ScriptFullName,WScript.ScriptName,"")
The 2 simplest ways:
Replace(WScript.ScriptFullName, WScript.ScriptName, "")
Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\"))
wscript.echo Mid(WScript.ScriptFullName,1,InStrRev(WScript.ScriptFullName, "\"))

VBScript current directory + sub directory?

I am trying to get the path of a file that is within a sub-directory of the current directory in VBScript. The following does not seem to work?
currentDirectory = left(WScript.ScriptFullName,(Len(WScript.ScriptFullName))-(len(WScript.ScriptName)))
FileToCopy = currentDirectory & "\test\user.js"
Here is the entire code:
Set oFSO = CreateObject("Scripting.FileSystemObject")
strFolder = oFSO.GetParentFolderName(WScript.ScriptFullName)
FileToCopy = oFSO.BuildPath(strFolder, "unproxy\user.js")
''# get AppdataPath
Set WshShell = CreateObject("WScript.Shell")
Set WshSysEnv = WshShell.Environment("PROCESS")
AppdataPath = WshSysEnv("APPDATA")
FoxProfilePath = AppdataPath & "\Mozilla\Firefox\Profiles\"
'"# is firefox and user.js present?
if oFSO.FolderExists(FoxProfilePath) AND oFSO.FileExists(FileToCopy) Then
''# copy user.js in all profilefolders to get around those random profile names =)
For Each ProfileFolder In oFSO.GetFolder(FoxProfilePath).Subfolders
oFSO.GetFile(FileToCopy).Copy ProfileFolder & "\" & FileToCopy, True
Next
End If
'"# clean up
Set oFSO = Nothing
Set WshShell = Nothing
Set WshSysEnv = Nothing
I recommend using FileSystemObject when dealing with file paths:
Set oFSO = CreateObject("Scripting.FileSystemObject")
strFolder = oFSO.GetParentFolderName(WScript.ScriptFullName)
FileToCopy = oFSO.BuildPath(strFolder, "test\user.js")
Edit: The problem is in this line of your script:
oFSO.GetFile(FileToCopy).Copy ProfileFolder & "\" & FileToCopy, True
Since FileToCopy contains a full file name, when you concatenate it with ProfileFolder you get an invalid file name, like this:
C:\Documents and Settings\username\Application Data\Mozilla\Firefox\Profiles\mlreq6kv.default\D:\unproxy\user.js
Change this line to the one below, and your script should work fine. (Note: the trailing path separator at the end of ProfileFolder is required to indicate that the profile folder, e.g. mlreq6kv.default, is indeed a folder and not a file.)
oFSO.GetFile(FileToCopy).Copy ProfileFolder & "\", True
You can get the current directory with :
Set WSHShell = WScript.CreateObject("WScript.Shell")
WScript.Echo WshShell.CurrentDirectory

Resources