How to search a folder name at a particular location, with a wildcard character and store in a variable? - firefox

This is the script I have written and I have mentioned the issue I am facing below.
Option Explicit
Dim FSO, WSH, RunDefaultProfile
Dim PF, UPF
Set FSO = CreateObject("Scripting.FileSystemObject")
Set WSH = CreateObject("Wscript.Shell")
UPF = Wsh.ExpandEnvironmentStrings("%userprofile%")
PF = Wsh.ExpandEnvironmentStrings("%ProgramFiles(x86)%")
RunDefaultProfile = """" & PF & "\Mozilla Firefox\firefox.exe" & """" & _
" -CreateProfile default"
' Create the Default profile if it not exists
If NOT FSO.FolderExists (UPF & "\AppData\Roaming\Mozilla\Firefox\Profiles\c4ssju9t.default") Then
WSH.Run RunDefaultProfile
End if
Now the challenge I am facing is, Firefox creates a random .default folder on each machine and I can't use my If NOT FSO.FolderExists condition. Also I want store the .default folder name if already exists. I will use that to run other commands and expand my script.

The path to the profile is stored in the file %APPDATA%\Mozilla\Firefox\profiles.ini. You can read it from the file like this:
Set fso = CreateObject("Scripting.FileSystemObject")
Set sh = CreateObject("WScript.Shell")
configdir = sh.ExpandEnvironmentStrings("%APPDATA%\Mozilla\Firefox")
inifile = fso.BuildPath(configDir, "profiles.ini")
If fso.FileExists(inifile) Then
Set f = fso.OpenTextFile(inifile)
Do Until f.AtEndOfStream
line = f.ReadLine
If Left(line, 5) = "Path=" Then
relPath = Split(line, "=")(1)
Exit Do
End If
Loop
f.Close
End If
This will get the first profile path from the INI file (if it exists).
You can then use it like this to create a missing profile:
profileExists = False
If Not IsEmpty(relPath) Then
profile = fso.BuildPath(configdir, relPath)
profileExists = fso.FolderExists(profile)
End If
If Not profileExists Then sh.Run RunDefaultProfile

Related

VBS script to rename files using the pathname

i am new to VBS scripting and I have done few stuff with Excel VBA before. Now I have a script which renames single files with the pathname of the files (truncated to 4 letter each))see below. It is some script which I modified a bit to fit my purpose. However, I would like to automatize the file rename process and rename all files in a folder and its subfolders in the same way the scipt works for single files. Can anybody help me with this question?
Set Shell = WScript.CreateObject("WScript.Shell")
Set Parameter = WScript.Arguments
For i = 0 To Parameter.Count - 1
Set fso = CreateObject("Scripting.FileSystemObject")
findFolder = fso.GetParentFolderName(Parameter(i))
PathName = fso.GetAbsolutePathName(Parameter(i))
FileExt = fso.GetExtensionName(Parameter(i))
Search = ":"
findFolder2= Right(PathName, Len(PathName) - InStrRev(PathName, Search))
arr = Split(findFolder2, "\")
For j=0 To UBound(arr)-1
arr(j) = ucase(Left(arr(j), 4))
Next
joined = Join(arr, "%")
prefix = right(joined, len(joined)-1)
fso.MoveFile Parameter(i), findFolder + "\" + prefix
next
Hoping that I can get some useful ideas.
Herbie
Walking a tree requires recursion, a function calling itself for each level.
On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
Dirname = InputBox("Enter Dir name")
ProcessFolder DirName
Sub ProcessFolder(FolderPath)
On Error Resume Next
Set fldr = fso.GetFolder(FolderPath)
Set Fls = fldr.files
For Each thing in Fls
msgbox Thing.Name & " " & Thing.DateLastModified
Next
Set fldrs = fldr.subfolders
For Each thing in fldrs
ProcessFolder thing.path
Next
End Sub
From Help on how to run another file.
Set Shell = WScript.CreateObject("WScript.Shell")
shell.Run(strCommand, [intWindowStyle], [bWaitOnReturn])
So outside the loop,
Set Shell = WScript.CreateObject("WScript.Shell")
And in the loop
shell.Run("wscript Yourscript.vbs thing.name, 1, True)
Also the VBS help file has recently been taken down at MS web site. It is available on my skydrive at https://1drv.ms/f/s!AvqkaKIXzvDieQFjUcKneSZhDjw It's called script56.chm.

Setting a file object by using a variable with .Files

I'm using this with HP Operations Manager, which uses the PARAMETER section so you can define variables from within the HPOM policy. This currently works for the one file hardcoded, but I want to be able to use the PARAMETER to set a filename, so the script is universal.
What this does is to check whether a specific file exists, and sets a variable (Rule.Status = True) if it is older than some amount of minutes specified in the FileAge variable.
Right now I am using:
Set MonitorFile = MonitorFolder.Files("EDI.001")
That works fine. But when I try to do:
Set MonitorFile = MonitorFolder.Files(FileName)
It fails with following error:
Invalid procedure call or argument.
Am I doing something wrong? Is there a better way of using a variable in this scenario?
Here is the whole script:
'PARAMETERS START
'PARAMETER FolderName STRING DEFAULT "D:\RFInput\InBoxPO" VALUE "D:\RFInput\InBoxPO\" SESSION
Dim FolderName
FolderName = "D:\RFInput\InBoxPO\"
Session("FolderName") = FolderName
'PARAMETER FileAge INT DEFAULT "60" VALUE "1" SESSION
Dim FileAge
FileAge = 1
Session("FileAge") = FileAge
'PARAMETER FolderDisplayName STRING DEFAULT "InBoxPO" VALUE "InBoxPO" SESSION
Dim FolderDisplayName
FolderDisplayName = "InBoxPO"
Session("FolderDisplayName") = FolderDisplayName
'PARAMETER FileName STRING DEFAULT "EDI.001" VALUE "EDI.001" SESSION
Dim FileName
FileName = "EDI.001"
Session("FileName") = FileName
'PARAMETERS END
Dim fs, MonitorFolder, MonitorFile, objShell, MinutesOld
Dim objFile, listNames
' Set constants for working with files
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Set objShell = CreateObject("Shell.Application")
Set fs = CreateObject("Scripting.FileSystemObject")
Set MonitorFolder = fs.GetFolder(FolderName)
Rule.Status = False
For Each objFile In MonitorFolder.Files
listNames = objFile.Name
If InStr(listNames, FileName) = 1 Then
Set MonitorFile = MonitorFolder.Files("EDI.001")
MinutesOld = DateDiff("n", MonitorFile.DateLastModified, Now)
If MinutesOld > FileAge Then
'Turn on for debugging - Wscript.Echo FileName & " is older than " & FileAge & " minutes in folder " & FolderName & "."
Rule.Status = True
End If
End If
Next
Set objShell = Nothing
Set fs = Nothing
Set MonitorFolder = Nothing
'END OF SCRIPT
Indeed access to specific items in the Files collection seems to work only with string literals, not sure why that is.
You can simplify the For Each loop, though:
For Each objFile In MonitorFolder.Files
If LCase(objFile.name) = LCase(FileName) Then
Set MonitorFile = objFile
...
End If
Next
If you require lookup by filename you could build a dictionary like this:
Set filenames = CreateObject("Scripting.Dictionary")
For Each objFile In MonitorFolder.Files
filenames.Add objFile.Name, objFile
Next
That will allow you to access the files by name like this:
Set MonitorFile = filenames(FileName)

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

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