Changing a file name using VBScript - vbscript

Hi I succeed changing a file name using VBS by using this code:
Set fso = CreateObject("Scripting.FileSystemObject")
set oFldr = fso.getfolder("C:\v\t_TEST\")
for each ofile in oFldr.Files
if lcase(fso.GetExtensionName(ofile.Name)) = "txt" then
ofile.name = "index.txt"
Exit for
end if
Next
Now I would like to make every .txt file placed on folder "v" (subfolders) to change it name also.
Or to define a changing path ("C:\v\t_XXX), so each folder starts with t_ in this path will change inside it all files end with .txt.
How do I do that?
Thanks!

I believe this is what you are looking for....
Set fso = CreateObject("Scripting.FileSystemObject")
Set oFldr = fso.getfolder("C:\v\")
For Each fld In ofldr.SubFolders
If Left(fld.name, 2) = "t_" Then
Set ofls = fso.GetFolder("C:\v\" & fld.name & "\")
For Each ofile In ofls.Files
If LCase(fso.GetExtensionName(ofile.Name)) = "txt" Then
ofile.name = "index.txt"
Exit For
End If
Next
End If
Next

Related

How to rename a file and overwrite existing in VBS?

I already an existing vbs script to take one file (titled "Running_12345.xlsx") from one location and put it in the folder titled "Folder". This is an hourly file that has a long name based on what time it was run.
Now, I want to rename the file just "Running.xlsx" to remove the constantly changing file name. Initially, this code works, but for any subsequent occurence, it fails because the "Running.xlsx" file has already been renamed once and now already exists. How do I add overwrite logic to this code:
dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
set oFldr = fso.getfolder("folder")
for each ofile in oFldr.Files
if lcase(fso.GetExtensionName(ofile.Name)) = "xlsx" then
ofile.name = "Running.xlsx"
Exit for
end if
Next
Duh, just delete the file first. The code below does what I want:
dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
set oFldr = fso.getfolder("C:\Users\...\Desktop\MosaicTransforms\")
fso.DeleteFile("C:\Users\...\Desktop\MosaicTransforms\MosaicFile.xlsx")
for each ofile in oFldr.Files
if lcase(fso.GetExtensionName(ofile.Name)) = "xlsx" then
ofile.name = "MosaicFile.xlsx"
Exit for
end if
Next

Need to move a variable folder based on date

This is what I have.
stSourceFolder = "C:\Users\HIRENS\Admin\" & Replace(CStr(Date()), "/", ".")
stTargetFolder = "C:\Users\HIRENS\Admin\HIRENS\Admin\backup\" & _
Replace(CStr(), "DDMMYY")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set fso = CreateObject("Scripting.FileSystemObject")
' The script will error out if it tries to create a directory that already exist
' so it is better to check for it first and only attempt to create it if it does
' not exist.
If Not fso.FolderExists(strDirectory) Then
' If it gets here then the folder for the current date does not yet exist and
' therefore is created.
Set objFolder = fso.CreateFolder(stTargetFolder)
End If
' This copies the files and overwrites them if they exist.
fso.CopyFolder stSourceFolder, destinationDir, OverwriteExisting
' If you entend to automate this script you should remove or rem out this next
' line.
WScript.Echo "Done"
'If the target-folder does not exist then it will be created.
objFSO.CopyFolder stSourceFolder, stTargetFolder
MsgBox "Folder copied"
Set fsoObj = Nothing
`On Error Resume Next
Dim sb : Set sb = CreateObject("System.Text.StringBuilder")
sb.AppendFormat "{0:ddMMyy}", Now() -1
'-----------------------------------------------------
TargetFolder = "C:\Users\"& sb.ToString &""
Set x = CreateObject("Scripting.FileSystemObject")
x.MoveFolder ""& TargetFolder &"" , "C:\Users\backup\"
'^^^ To move Variable folder DDMMYY
'------------------------------------------------------------
Dim fso, count, src, folder, file
Set fso = CreateObject("Scripting.FileSystemObject")
src = "C:\Users\backup\"& sb.ToString &"\"
stringtofind = "txt"
Set folder = fso.GetFolder(src)
count = 0
For Each file In folder.files
If instr(LCase(file.name), LCase(stringtofind)) > 0 Then
count = count + 1
End If
Next
WScript.Echo "PXE Files Count: " & count`

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

Iterate through the folder and find a particular file

I have written this code to iterate through the folders and exit the function when it finds the ".c" file. Ideally it should return the path of the ".c" file. But its returning empty string.
tval = 1
Function findStlcode(objFSO,fFolder,folderName)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set Folder = objFSO.GetFolder(fFolder)
Set colfiles = Folder.Files
For Each objFile In colfiles
strFilename = objFile.name
If strcomp(strFilename,folderName & ".c",vbTextCompare) = 0 Then
findStlcode = fFolder & "\" & folderName & ".c"
tval = tval + 1
Exit Function
End If
Next
For Each Subfolder In Folder.SubFolders
If tval = 1 Then
xx = findStlcode(objFSO, Subfolder.Path, folderName)
End If
Next
End Function
Change the FOR loop contents to below, change xx to findStlcode and it should work
strFilename = objFile.name
If Right(strFilename, 2) = ".c" Then
findStlcode = fFolder & "\" & strFilename
tval = tval + 1
Exit Function
End If
Complete code below
tval = 1
Function findStlcode(objFSO,fFolder)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set Folder = objFSO.GetFolder(fFolder)
Set colfiles = Folder.Files
For Each objFile In colfiles
strFilename = objFile.name
If Right(strFilename, 2) = ".c" Then
findStlcode = fFolder & "\" & strFilename
tval = tval + 1
Exit Function
End If
Next
For Each Subfolder In Folder.SubFolders
If tval = 1 Then
findStlcode = findStlcode(objFSO, Subfolder.Path)
End If
Next
End Function
Calling the Function
Set objFSO = CreateObject("Scripting.FileSystemObject")
Wscript.Echo findStlcode(objFSO, "C:\")
The root cause of your problem is that your function doesn't actually return the path (by assigning it to the function name), as others have already pointed out.
There are, however, some other issues with your implementation that you may want to address:
You shouldn't use a global variable to keep track of whether a matching file was found or not. The return value of the recursive function calls can be used to the same effect.
There's no point in passing objFSO if you're going to re-create it with each function call anyway. In practically every case it's better to create a FileSystemObject instance as a global (singleton) object and use that everywhere in your script.
Pass folder objects instead of path strings, so you don't have to turn the string back into a folder object in the next recursion step.
If you're going to check for an extension, use the appropriate method to extract the extension from a file name (GetExtensionName).
Something like this would suffice:
Set fso = CreateObject("Scripting.FileSystemObject")
Function findStlcode(fldr)
Dim f, sf, path
For Each f In fldr.Files
If LCase(fso.GetExtensionName(f)) = "c" Then
path = f.Path
Exit For
End If
Next
For Each sf In fldr.SubFolders
If IsEmpty(path) Then path = findStlcode(sf)
Next
findStlcode = path
End Function
startFolder = "C:\some\folder"
cfile = findStlCode(fso.GetFolder(startFolder))

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