How to find and read file using wild cards with VBscript? - file

I am trying unsuccessfully to read an XML file (The file name is change in each computer).
How it possible to read the file using wild card?
for example: D:\Logs\*.xml
Script:
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("D:\Logs\*.xml", ForReading)
strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "server1 ", "server889 ")
Set objFile = objFSO.OpenTextFile("D:\Logs\*.xml", ForWriting)
objFile.WriteLine strNewText
objFile.Closeenter code here

There is no wild card in VBScript. Repeat your group of statements for each element in Files collection of Folder object obtained by GetFolder Method:
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("D:\Logs")
Set colFiles = objFolder.Files
For Each oFile in colFiles
If UCase(objFSO.GetExtensionName(oFile.name)) = "XML" Then
Set objFile = objFSO.OpenTextFile(oFile.Path, ForReading)
strText = objFile.ReadAll
objFile.Close
If Instr( 1, strText, "server1 ", vbTextCompare) > 0 Then
strNewText = Replace(strText, "server1 ", "server889 ", 1, -1, vbTextCompare)
Set objFile = objFSO.OpenTextFile(oFile.Path, ForWriting)
objFile.WriteLine strNewText
objFile.Close
End If
End If
Next
Resource: FileSystemObject

Related

How to run more than one batch with vbs and set batch file path using environment variables? [duplicate]

This question already has an answer here:
How to get %username% in VBScript?
(1 answer)
Closed 3 years ago.
I have this script (courtesy of #WesternSage) that renames foo.txt to foo.bat, launches foo.bat, and when foo.bat ends, renames it back to foo.txt.
Dim Fso
Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
Fso.MoveFile "foo.txt", "foo.bat"
SCRIPT = "foo.bat"
Set objShell = CreateObject("WScript.Shell")
strPath = WScript.ScriptFullName
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(strPath)
strFolder = objFSO.GetParentFolderName(objFile)
NewPath = objFSO.BuildPath(strFolder, SCRIPT)
Set objshell = createobject("wscript.shell")
objshell.Run "%COMSPEC% /c " & NewPath, 1, True
' Changes start here
'===================================================================
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
' Hold execution until cmd.exe process is done
Do
' Get cmd.exe processes
Set colProcessList = objWMIService.ExecQuery _
("SELECT Name FROM Win32_Process WHERE Name LIKE 'cmd.exe'")
WScript.Sleep 250
Loop While colProcessList.Count > 0
Fso.MoveFile "foo.bat", "foo.txt"
The problem is:
foo.txt (foo.bat) is in a path, which can change depending on the Windows version. For this I need to use environment variables to set the foo.txt path (example: %homedrive%), but this change doesn't work.
SCRIPT = "%homedrive%\test\foo.bat"
I need to call a second batch (bar.bat), when the first one ends (foo.bat). But this change does not work at the end of .vbs.
Dim Fso
Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
Fso.MoveFile "%homedrive%\test\bar.txt", "%homedrive%\test\bar.bat"
SCRIPT = "%homedrive%\test\bar.bat"
Set objShell = CreateObject("WScript.Shell")
strPath = WScript.ScriptFullName
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(strPath)
strFolder = objFSO.GetParentFolderName(objFile)
NewPath = objFSO.BuildPath(strFolder, SCRIPT)
set objshell = createobject("wscript.shell")
objshell.Run "%COMSPEC% /c " & NewPath, 1, True
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
' Hold execution until cmd.exe process is done
Do
' Get cmd.exe processes
Set colProcessList = objWMIService.ExecQuery _
("SELECT Name FROM Win32_Process WHERE Name LIKE 'cmd.exe'")
WScript.Sleep 250
Loop While colProcessList.Count > 0
Fso.MoveFile "%homedrive%\test\bar.bat", "%homedrive%\test\bar.txt"
This should works:
Dim Fso
Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
set objshell = createobject("wscript.shell")
homedrive = objshell.ExpandEnvironmentStrings( "%HOMEDRIVE%" )
Fso.MoveFile homedrive & "\test\bar.txt", homedrive & "\test\bar.bat"
SCRIPT = homedrive & "\test\bar.bat"
strPath = Wscript.ScriptFullName
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(strPath)
strFolder = objFSO.GetParentFolderName(objFile)
NewPath = objFSO.BuildPath(strFolder, SCRIPT)
set objshell = createobject("wscript.shell")
objshell.Run (script),1,True
Fso.MoveFile homedrive & "\test\bar.bat", homedrive & "\test\bar.txt"

Read from array one by one - VBScript

I am trying to read from a file, create an array, then write to a second file line by line (element by element) while adding some additional information. The script below will read correctly from a file, but will only write the last line in the initial file. How can I write from the array one at a time? (I can write the contents to the second file in a different manner, but I want to do it directly from the array).
Const ForReading = 1, ForWriting = 2, ForAppending = 3
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(input,
ForReading)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
arrFields = Split(strLine, ",")
If InStr(arrFields(1), "False") Then
strContents = strContents & arrFields(0) & vbCrlf
End If
Loop
objFile.Close
Set objFile = objFSO.CreateTextFile(output)
' below correctly outputs contents
' objFile.Write strContents
For each i in arrFields
objFile.Write arrFields(0)
objFile.Write "Number" & vbCrlf
Next
objFile.Close
My test csv file reads as below saved as "test.csv" from notepad.
1,FALSE
2,FALSE
3,FALSE
4,FALSE
5,FALSE
6,FALSE
7,FALSE
8,FALSE
9,FALSE
10,FALSE
11,FALSE
12,FALSE
13,TRUE
Sample code
Const ForReading = 1, ForWriting = 2, ForAppending = 3
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Users\pankaj.jaju\Desktop\test.csv", ForReading)
arrFields = Split(objFile.ReadAll, vbCrLf)
objFile.Close
Set objFile = objFSO.CreateTextFile("C:\Users\pankaj.jaju\Desktop\test1.txt")
For i = LBound(arrFields) To UBound(arrFields)
objFile.Write "Number " & i+1 & "," & Split(arrFields(i),",")(0) & vbCrlf
Next
objFile.Close

VBS script to copy files and folders across network

I needed to copy all of my photos from my old laptop to my new laptop. This is a quick and dirty script that I put together (based on other scripts on this site) to copy files from one network location to another. I wanted the process to be able to recover in case of a network copy error because the total time to copy all of my photos was 40 hours.
sourceRoot and targetRoot is the beginning part of the file path to replace between locations. lastFileLog is a file used to keep track of the last file that was copied. This is needed to recover from a partial copy. Windows seems to allocate the full file size even when the file fails to copy. So I just keep track of the last file to copy it again on failure. objStartFolder is the starting path on the source network location.
'initialize paths
objStartFolder = "\\owner-pc\d\pics"
lastFileLog = "c:\Files\misc\archive.log"
sourceRoot = "\\owner-pc\d"
targetRoot = "c:\Files"
Set objFSO = CreateObject("Scripting.FileSystemObject")
'read log
Set objFile = objFSO.OpenTextFile(lastFileLog)
Do Until objFile.AtEndOfStream
replacefile= objFile.ReadLine
Wscript.Echo "This file will be replaced: " & replacefile
Loop
objFile.Close
'copy files
Set objFolder = objFSO.GetFolder(objStartFolder)
ShowSubfolders objFSO.GetFolder(objStartFolder)
'clear log
Set objFileLog = objFSO.CreateTextFile(lastFileLog,True)
objFileLog.Write ""
objFileLog.Close
Sub ShowSubFolders(Folder)
For Each Subfolder in Folder.SubFolders
Wscript.Echo Subfolder.Path
if not(objFSO.FolderExists(replace(Subfolder.Path,sourceRoot,targetRoot))) then
objFSO.CreateFolder(replace(Subfolder.Path,sourceRoot,targetRoot))
end if
Set objFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objFolder.Files
For Each objFile in colFiles
if not(objFSO.FileExists(replace(Subfolder.Path & "\" & objFile.Name,sourceRoot,targetRoot))) then
Wscript.Echo Subfolder.Path & "\" & objFile.Name
Set objFileLog = objFSO.CreateTextFile(lastFileLog,True)
objFileLog.Write Subfolder.Path & "\" & objFile.Name
objFileLog.Close
objFSO.CopyFile Subfolder.Path & "\" & objFile.Name, replace(Subfolder.Path & "\" & objFile.Name,sourceRoot,targetRoot)
elseif replacefile = Subfolder.Path & "\" & objFile.Name then
Wscript.Echo "Replacing ... " & Subfolder.Path & "\" & objFile.Name
objFSO.CopyFile Subfolder.Path & "\" & objFile.Name, replace(Subfolder.Path & "\" & objFile.Name,sourceRoot,targetRoot),true
else
Wscript.Echo "Skip ... " & Subfolder.Path & "\" & objFile.Name
end if
Next
ShowSubFolders Subfolder
Next
end sub
For Folder: Try This.
Option Explicit
Dim obj,Itemcoll1,a,b
Set obj=CreateObject("Shell.Application")
Function SelectFold1(Desc)
Set SelectFold1=obj.BrowseForFolder(0,Desc,0,"C:\Users\Mohammed Sajjad\Desktop\")
End Function
Set Itemcoll1=SelectFold1("Copy: ").Items
SelectFold1("Paste: ").CopyHere Itemcoll1 'Use MoveHere if you want to move
MsgBox "Completed"
For File:
Option Explicit
Dim objApp : Set objApp = CreateObject("Shell.Application")
Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objSHL : Set objSHL = CreateObject("WScript.Shell")
'Browse for Folder
'----------------------------------------------------------
Function SelectFold()
Dim objFolder
Set objFolder = objApp.BrowseForFolder(0,"Select a Folder",0,0)
If objFolder Is Nothing Then
MsgBox "Canceled"
WScript.Quit
Else
SelectFold = objFolder.Self.Path & "\"
End If
End Function
'----------------------------------------------------------
'Browse for file
'----------------------------------------------------------
Function SelectFile()
Dim tempFolder : Set tempFolder = objFSO.GetSpecialFolder(2)
Dim tempFile : tempFile = objFSO.GetTempName() & ".hta"
Dim path : path = "HKCU\Volatile Environment\MsgResp"
With tempFolder.CreateTextFile(tempFile)
.Write "<input type=file name=f>" & _
"<script>f.click();(new ActiveXObject('WScript.Shell'))" & _
".RegWrite('HKCU\\Volatile Environment\\MsgResp', f.value);" & _
"close();</script>"
.Close
End With
objSHL.Run tempFolder & "\" & tempFile, 0, True
If objSHL.RegRead(path) = "" Then
objSHL.RegDelete path
objFSO.DeleteFile tempFolder & "\" & tempFile
WScript.Quit
End If
SelectFile = objSHL.RegRead(path)
objSHL.RegDelete path
objFSO.DeleteFile tempFolder & "\" & tempFile
End Function
'----------------------------------------------------------
objFSO.CopyFile SelectFile, SelectFold

vbs read from file and parse it to the batch file

I had a script which worked on win xp but beacuse some of the methods are not available anymore I had to rewrite the script and use mshta.exe.
VBS script should do two things:
Read from file
Parse the info to the batch file
I have done the 1st bit but in the 2nd part I am getting an error. Could you please point me to the right direction?
Option Explicit
Dim objFso
Dim strFileName
Dim strFile
Dim objShell
Dim cimv2
Dim RemoteMachine
Dim YesNo
Dim out
Dim crt
Dim objDialog, intResult
Dim objTextFile, strText, iintresult
Dim objExec, strMSHTA, wshShell
mainMenu
Sub mainMenu()
do
out = inputbox("Choose option:" & vbcr & "1 - Deployment" & vbcr & "0 - Exit", "Menu", "0")
If out="1" then
call SelectFile
End If
If out="0"
then WScript.Quit
End if
loop
End Sub
Sub bgInfo(param)
YesNo = Msgbox("deployment? " & param, 4)
if YesNo = vbYes Then
do while not strMSHTA.AtEndOfStream
RemoteMachine = strMSHTA.ReadLine()
On Error Resume Next
objShell.Run "bginfo.bat " & RemoteMachine, 1, true
On Error Goto 0
loop
end if
End Sub
Sub SelectFile( )
strMSHTA = "mshta.exe ""about:" & "<" & "input type=file id=FILE>" _
& "<" & "script>FILE.click();new ActiveXObject('Scripting.FileSystemObject')" _
& ".GetStandardStream(1).WriteLine(FILE.value);close();resizeTo(0,0);" & "<" & "/script>"""
Set wshShell = CreateObject( "WScript.Shell" )
Set objExec = wshShell.Exec( strMSHTA )
intResult = objExec.StdOut.ReadLine( )
msgbox iintresult
If intResult <> "" Then
call bgInfo(intResult)
End If
Set objExec = Nothing
Set wshShell = Nothing
End Sub
Set objFso = Nothing
Set strFileName = Nothing
Set strFile = Nothing
Set objShell = Nothing
Set cimv2 = Nothing
Set RemoteMachine = Nothing
Set fso = Nothing
I am getting an error in line 33 char 5
Error: Object required: strMSHTA
thank you! :)
I had to add this code:
Set objFso = CreateObject("Scripting.FileSystemObject")
set strFile = objFso.OpenTextFile(param2, 1, True)
Set objShell = WScript.CreateObject("Wscript.Shell")`

How to make a batch file edit a text file

I got the code
Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "C:\test\file.txt"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
If InStr(strLine,"ex3")> 0 Then
strLine = Replace(strLine,"ex3","ex5")
End If
WScript.Echo strLine
Loop
The strLine replacing part i can fix myself to use with my own purposes, but how do i do something like this so that it doesn't require the file's name, it just edits all text files within the document?
you can do it like this,
strFolder = "c:\myfolder"
Set objFolder = objFS.GetFolder(strFolder)
For Each strFile In objFolder.Files
strFileName =strFile.Name
strFilePath = strFile.Path
strFileExt = objFS.GetExtensionName(strFile)
If strFileExt = "txt" Then
Set objFile = objFS.OpenTextFile(strFile)
' your current code here..
objFile.Close()
End If
Next

Resources