How to Copy a file that was read from a list - vbscript

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

Related

VBScript command to wait for files to be extracted before launching EXE to install program

I'm looking at having a script that decompresses a file (PDMsetup.zip) and then launch the executable that it extracts.
ZipFile="PDMsetup.zip"
ExtractTo=".\"
Set fso = CreateObject("Scripting.FileSystemObject")
sourceFile = fso.GetAbsolutePathName(ZipFile)
destFolder = fso.GetAbsolutePathName(ExtractTo)
Set objShell = CreateObject("Shell.Application")
Set FilesInZip=objShell.NameSpace(sourceFile).Items()
objShell.NameSpace(destFolder).copyHere FilesInZip, 16
Set fso = Nothing
Set objShell = Nothing
Set FilesInZip = Nothing
wscript.sleep 480000
Set objShell = CreateObject("Wscript.Shell")
strPath = Wscript.ScriptFullName
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(strPath)
strFolder = objFSO.GetParentFolderName(objFile)
strPath = strFolder & "\Startwinstall.exe"
objShell.Run strPath
I want to get rid of;
wscript.sleep 480000
and replace it with a command that tells the script wait until the extraction is done before launching startwinstall.exe
I've kept adjusting the wait time to make up for differences in PC performance with the extraction, but a command to just 'wait' until it's done would be preferential.
Delete any previous copy of the installer exe in the target folder and then wait for that file to be created. Create your objects once at the top of the script. And there's no need to set the objects to Nothing. That will happen automatically when the script ends. The edited script is below:
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oWSH = CreateObject("Wscript.Shell")
Set oApp = CreateObject("Shell.Application")
MyFolder = oFSO.GetParentFolderName(WScript.ScriptFullName)
ExtractTo = ".\"
ZipFile = "PDMsetup.zip"
StartApp = ExtractTo & "Startwinstall.exe"
On Error Resume Next
oFSO.DeleteFile StartApp
On Error Goto 0
sourceFile = oFSO.GetAbsolutePathName(ZipFile)
destFolder = oFSO.GetAbsolutePathName(ExtractTo)
Set FilesInZip = oApp.NameSpace(sourceFile).Items()
oApp.NameSpace(destFolder).copyHere FilesInZip, 16
Do Until oFSO.FileExists(StartApp)
WScript.Sleep 1000
Loop
oWSH.Run StartApp
Note: I assigned a MyFolder variable, but it's not currently being used. ExtractTo = ".\" could be changed to ExtractTo = MyFolder. You could also eliminate the GetAbsolutePathName lines if you are using MyFolder with the ZipFile name. There are always many ways to do the same thing.
Note: I think the above can be done with a much briefer (probably two line) PowerShell script. Let me know if you're interested in that solution.

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.

Read a line from several .txt files and write them into created file

I have a quite simple task.
There is a folder which contains several files with different extensions. I need to make a script which will find all files with .txt extension in this folder, read first line from every file and then write all first lines in newly created file.
For now, I've ended up with something like this:
Option Explicit
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Dim f, colFiles , objFile
Dim tFolder, tFile
Dim lineToCopy, fileContents
Dim input, output
Set tFolder = fso.GetFolder("C:\Temp")
Set tFile = tFolder.CreateTextFile("test.txt", true)
Set f = fso.GetFolder("D:\Folder")
Set colFiles = f.Files
For Each objFile in colFiles
If LCase(fso.GetExtensionName(objFile.name)) = "txt" Then
Set input = fso.OpenTextFile(LCase(objFile.name))
If Not input.AtEndofStream Then lineToCopy = input.ReadLine
input.close
output = fso.OpenTextFile(tFolder, True)
output.WriteLine lineToCopy
output.close
End If
Next
WScript.sleep 60000000
When activated, .vbs file tells me he couldn't find the file from that line:
Set input = fso.OpenTextFile(LCase(objFile.name))
I suppose that happens because IF LCASE<...> block doesn't understand folder contents as .txt files. Where am I wrong and what is needed to be done to solve that problem?
Kindly yours,
Richard
Use the full .Path of the file for OpenTextFile or get the stream via OpenAsTextStream. Use tFile instead of repeatedly creating output. Delete all the risky/cargo cult fat:
Option Explicit
Dim fso : Set fso = CreateObject("Scripting.FileSystemObject")
Dim tFile : Set tFile = fso.CreateTextFile(fso.BuildPath(".\", "test.txt"))
Dim oFile
For Each oFile in fso.GetFolder("..\data").Files
If LCase(fso.GetExtensionName(oFile.Path)) = "txt" Then
' Dim input: Set input = fso.OpenTextFile(LCase(oFile.Path))
Dim input: Set input = oFile.OpenAsTextStream()
If Not input.AtEndofStream Then tFile.WriteLine input.ReadLine()
input.Close
End If
Next
tFile.Close
Looks like I've found my own decision:
Option Explicit
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Dim f, colFiles , objFile
Dim tFolder, tFile
Dim lineToCopy, readFile
Set tFolder = fso.GetFolder("C:\Temp")
Set tFile = tFolder.CreateTextFile("test.txt", true)
Set f = fso.GetFolder("D:\Scripting Games 2008\Beginner")
Set colFiles = f.Files
For Each objFile in colFiles
If LCase(fso.GetExtensionName(objFile.name)) = "txt" Then
REM Preceding passage finds all .txt files in selected folder
Set readFile = objFile.OpenAsTextStream
lineToCopy = ""
Do Until lineToCopy <> "" Or readfile.atEndOfStream
lineToCopy = Trim(readFile.ReadLine)
Loop
REM Extracts first line of the text, if it is not empty
tFile.WriteLine objFile.name & ": " & lineToCopy
End If
Next
Still, thanks for the answers. I've found some interesting solutions which well be of use some time.
Kindly yours,
Richard

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

vbscript : fso.opentextfile permission denied

In my code segment, when I script the file name, it gives me a permission denied
on the following line:
Set objTextFile = objFSO.OpenTextFile(strDirectory & strFile, ForAppending, True)
Here is the script
'output log info
Function OutputToLog (strToAdd)
Dim strDirectory,strFile,strText, objFile,objFolder,objTextFile,objFSO
strDirectory = "c:\eNet"
strFile = "\weeklydel.bat"
'strText = "Book Another Holiday"
strText = strToAdd
' Create the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Check that the strDirectory folder exists
If objFSO.FolderExists(strDirectory) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFolder = objFSO.CreateFolder(strDirectory)
'WScript.Echo "Just created " & strDirectory
End If
If objFSO.FileExists(strDirectory & strFile) Then
Set objFolder = objFSO.GetFolder(strDirectory)
Else
Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
'Wscript.Echo "Just created " & strDirectory & strFile
End If
set objFile = nothing
set objFolder = nothing
' OpenTextFile Method needs a Const value
' ForAppending = 8 ForReading = 1, ForWriting = 2
Const ForAppending = 2
Set objTextFile = objFSO.OpenTextFile(strDirectory & strFile, ForAppending, True)
' Writes strText every time you run this VBScript
objTextFile.WriteLine(strText)
objTextFile.Close
End Function
I have assigned the vbscript domain administrator permissions. Any ideas?
thanks in advance
I don't think this has to do with File Permissions per se. It has to do with the fact that you've created the file using:
Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
That creates the file...and carries a reference to that file (objFile)
Then you don't close the file before you destroy the reference
...
'Missing objFile.Close here
Set objFile = nothing
Set objFolder = nothing
...
Consequently you're destroying the reference but leaving the textstream open in memory thus locking your file.
You are then proceeding to attempt to re-open the file while the file is already "open". This is a little long winded, you've already got a reference after you've created the file - it would be easier just to write straight to that rather than destroy the reference before creating another one.
for what its worth...
I was convinced I had a permission error because of this line:
Set LogFile = LogFSO.OpenTextFile(LogFileName, ForWriting, True)
Because that's the line that the 'permission denied' error pointed to. But in fact, my permission error was a few lines further down:
WshShell.AppActivate(ScreensToRemove(i))
WshShell.SendKeys ("~")
WScript.Sleep(1000)
There was no screen with such a caption, so the SendKeys is what did not have permission.
The solution, of course, was:
If WshShell.AppActivate(ScreensToRemove(i)) = True Then
WshShell.SendKeys ("~")
WScript.Sleep(1000)
End if
Hope that might help.
Also, make sure that you don't have the file open in Excel (I had this problem with a .csv file)...
In my particular case the file which existed before and all I had to do was give permission to the Everyone user
balabaster is exactly right. You either need to close the file before reopening it a second time for writing, or using the existing open handle.

Resources