Vbs - File Cont \ File Delete - vbscript

I am creating a guy script read files in a folder, (Scripting.FileSystemObject), but I would like to relate a indice inpubox type int to determine which file in the folder I'll write on the screen.
Ex: indice = inputbox "" ← 4 grab the indice file in the folder 4 and esquever your name on the screen.
  I wonder if this is possible because already tried in many ways and even by matrix, but without result.
This and my code. I do not know but where to go!
Dim sFO, NovaPasta, Folder,File, Indice
Dim inpast(4)
'Setup
Set sFO = CreateObject("Scripting.FileSystemObject")
Set Folder = sFo.GetFolder("C:\Users\502526523\Documents\Control")
NovaPasta = "Control"
'Development
If Not sFO.FolderExists (NovaPasta) = True Then
sFO.CreateFolder (NovaPasta)
Wscript.Sleep 900
WScript.Echo "Pasta Criada"
Else
WScript.Echo "Pasta Existente "
End If
' Line Verificas a quantidade de inpastas dentro da pasta, se > 5
' deleta os exedentes com data mais antiga
For Each file In folder.Files
If Folder.Files.Count > 5 And (DateDiff("d", file.DateLastModified, Now) > 7) Then
WScript.Echo (file.Name & vbLf)
WScript.Echo ("Total files :" & Folder.Files.Count)
File.Delete
End If
Next
For Each file In folder.Files
inpast(0) = (file.Name)
inpast(1) = (file.Name)
inpast(2) = (file.Name)
inpast(3) = (file.Name)
inpast(4) = (file.Name)
Indice = Inputbox ("Digite o valor do Indice de 0...30")
Select Case Indice
Case 0
WScript.Echo inpast(0)
Case 1
WScript.Echo inpast(1)
Case 2
WScript.Echo inpast(2)
Case 3
WScript.Echo inpast(3)
Case 4
WScript.Echo inpast(4)
End Select
Next

Still not sure if I understand your question correctly. You mean you have a list of filenames and you want to display the filename corresponding to the number the user entered via an InputBox? If that's what you want you should change your second For Each loop like this:
i = 0
For Each file In folder.Files
inpast(i) = file.Name
i = i + 1
Next
Indice = InputBox("Digite o valor do Indice de 0...30")
WScript.Echo inpast(CInt(Indice))
Note, however, that the condition in your first For Each loop does not guarantee you'll only ever have 5 files left after the loop. If for some reason the folder contains more than 5 files that were modified within the past 7 days the second loop would fail with a "subscript out of range" error.
There are several ways you could handle this:
Dynamically resize the inpast array so it can hold more than 5 items.
Sort the files in the folder by last modification date (e.g. like this) and delete everything except the 5 most recent files.
Cut off the second For Each loop after the 5th iteration (Exit For).
Note also, that you should sanitize your input. (What happens when users enter text, an invalid number, or press "Cancel"?)

Set fso = CreateObject("Scripting.FileSystemObject")
Dirname = InputBox("Enter Dir name")
'Searchterm = Inputbox("Enter search term")
ProcessFolder DirName
Sub ProcessFolder(FolderPath)
' On Error Resume Next
Set fldr = fso.GetFolder(FolderPath)
msgbox fls.count
Msgbox fls.item("computerlist.txt")
End Sub
To do the 7th
Set Fls = fldr.files
For Each thing in Fls
Count = Count + 1
If count = 7 then msgbox Thing.Name & " " & Thing.DateLastModified
Next

Related

How to recover the outlook emails for a deleted email account

I accidentally delete my email account and so all of the emails in that account. Is there a chance to recover the emails? How can I recover it? Thanks.
Four months ago I would have agreed with Om3r's comment giving the location of the Outlook stores. But I bought a new laptop in December and now the Outlook files are not where all the documentation says they should be. Worse, I cannot reach the folders containing the Outlook files using File Explorer although I can find them with VBA.
The macro below searches drive C for files with an extension of OST or PST. I cannot promise this macro will find your lost store but, if it is still on your disc, it will find it. If you find the missing store, you will probably have to use VBA to move it to somewhere accessible.
Copy the macro below to a macro-enabled workbook and run it. While it is running the active worksheet will look like:
1923 Folders to search
327 Folders searched
Store Size Date Folder
$ILJARJ0.pst 212 28Mar20 C:\$Recycle.Bin\S-1-5-21-3957073674-21115239-22921093-1001
$IMS96DJ.pst 212 28Mar20 C:\$Recycle.Bin\S-1-5-21-3957073674-21115239-22921093-1001
The top two rows give a crude progress indicator. On my laptop, the routine ends with 69190 folders searched. I do not know why there are PST files in my recycle bin. I did nothing relevant on 28 March. When the routine has finished, there will be a auto-fitted list of every store the macro found. On my laptop none are where I would expect and some are duplicates. I hope you find your store.
Option Explicit
Sub SearchForStoresOnC()
' Searches drive C for files with an extension of PST or OST
' Warning: overwrites the active workbook
Dim ErrNum As Long
Dim FileAttr As Long
Dim FileName As String
Dim FldrName As String
Dim RowCrnt As Long
Dim ToSearch As Collection
Cells.EntireRow.Delete
Range("A1").Value = 0
Range("A2").Value = 0
Range("B1").Value = "Folders to search"
Range("B2").Value = "Folders searched"
Range("B4").Value = "Store"
With Range("C4")
.Value = "Size"
.HorizontalAlignment = xlRight
End With
With Range("D4")
.Value = "Date"
.HorizontalAlignment = xlRight
End With
Range("E4") = "Folder"
RowCrnt = 5
Set ToSearch = New Collection
' Load ToSearch with drive to search.
ToSearch.Add "C:"
Do While ToSearch.Count > 0
FldrName = ToSearch(1)
ToSearch.Remove 1
Err.Clear
ErrNum = 0
On Error Resume Next
' Stores are unlikely to be hidden but can be in folders that are hidden
FileName = Dir$(FldrName & "\*.*", vbDirectory + vbHidden + vbSystem)
ErrNum = Err.Number
On Error GoTo 0
If ErrNum <> 0 Then
'Debug.Print "Dir error: " & FldrName
Else
Do While FileName <> ""
If FileName = "." Or FileName = ".." Then
' Ignore pointers
Else
Err.Clear
On Error Resume Next
FileAttr = GetAttr(FldrName & "\" & FileName)
ErrNum = Err.Number
On Error GoTo 0
If ErrNum = 0 Then
' Ignore file and folders which give errors
If (FileAttr And vbDirectory) = 0 Then
' File
'Debug.Assert False
Select Case Right$(FileName, 4)
Case ".pst", ".ost"
Cells(RowCrnt, "B").Value = FileName
With Cells(RowCrnt, "C")
.Value = FileLen(FldrName & "\" & FileName)
.NumberFormat = "#,##0"
End With
With Cells(RowCrnt, "D")
.Value = FileDateTime(FldrName & "\" & FileName)
.NumberFormat = "dmmmyy"
End With
Cells(RowCrnt, "E").Value = FldrName
RowCrnt = RowCrnt + 1
End Select
Else
' Directory
ToSearch.Add FldrName & "\" & FileName
End If ' File or Directory
Else
'Debug.Print "FileAttr error: " & FldrName & "\" & FileName
End If ' FileAttr does not give an error
End If ' Pointer or (File or Directory)
FileName = Dir$
Loop ' For each pointer, file and sub-directory in folder
End If ' Dir$ gives error
Range("A1") = ToSearch.Count
Range("A2") = Range("A2") + 1
DoEvents
Loop 'until ToSearch empty
Columns.AutoFit
End Sub

Configure Multi Disc Macrium Auto Restore .vbs file

A previous team where I work created a vbs script that can automatically start a restore of a Macrium Image File located on inserted optical media. The problem is that the Macrium Image File is now too big for one disc, and now we have it split onto 2 separate discs, so now the vbs script doesn't function the way it should.
When Automatic Restore is launched, it should detect disc 1, which ends in 00.00.mrimg and know that it is part of a multi-disc install, at which point it asks for the next disc, ending in 00-01.mrimg.
I know this probably makes no sense, especially if anyone reading is not familiar with Macrium. But I will do my best to answer any questions.
I would normally plug away and try to figure it out myself, but i'm not very familiar with VBS and the problem is pretty time sensitive. Any help I can get will be much appreciated.
Opened AutoRestore.vbs script to see if I could fix the issue, but I don't know enough about vbs to fix it.
'AutoRestore.vbs
Dim fso, d, dc, s, n , Root, u, racine, folder, folderName, restoreString, foundFile, cdDrive
Dim wipe
Dim objShell
Set objShell = WScript.CreateObject("WScript.shell")
Set fso = CreateObject("Scripting.FileSystemObject")
Set dc = fso.Drives
foundFile = false
restoreString = "00-00.mrimg"
For Each d in dc
Root = d.Driveletter & ":"
racine = d.Driveletter & ":\"
u= Detect(Root)
if (( u="CD-ROM") ) then
cdDrive = cdDrive & racine & " "
if (d.isReady) then
folderName = racine & "IAS\"
Set folder = fso.GetFolder(folderName)
end if
end if
Next
If IsNull(folder) or IsEmpty(folder) Then
MsgBox "Could not locate IAS folder containing restore image." & vbCrLf & "The following optical disk drives were searched: " & cdDrive & vbCrLf & "Please verify the media is the drive or use manual restore.", 48, "Folder Not Found"
Else
For each file in folder.Files
If instr(1,file.Name, restoreString, vbTextCompare) > 0 Then
return = objShell.run("""%ProgramFiles%\macrium\diskrestore.exe""" & folderName & file.Name & " -r -g -u --targetnum 0 --reboot --eject",1,false)
foundFile = true
Exit For
End If
Next
if (foundFile = false) Then
MsgBox "Cannot locate .mrimg file in " & folderName & "." & vbCrLf & "Please use manual restore.", 48, "File Not Found"
End If
End If
Function Detect(DrivePath)
Dim fso, d, s, t
Set fso = CreateObject("Scripting.FileSystemObject")
Set d = fso.GetDrive(fso.GetDriveName(fso.GetAbsolutePathName(DrivePath)))
Select Case d.DriveType
Case 0: t = "Unknown"
Case 1: t = "Removable"
Case 2: t = "Fixed"
Case 3: t = "Network"
Case 4: t = "CD-ROM"
Case 5: t = "RAM Disk"
End Select
Detect = t
End Function
Expected Results: Run AutoRestore.vbs, the script sees the 00-00.mrimg file in IAS folder of the optical media, then prompts to insert the optical media containing the 00-01.mrimg file.
Actual Results: Run AutoRestore.vbs, then Macrium states "Backup set is not complete. At least one file may be missing."
You could first copy all the mrimg files to a temporary folder on the machine's hard drive. Once you have them all, you can then run Disk Restore with that folder instead of the CD-ROM drive.
Most of your existing code would work. After the For Each d in dc loop, you know the drive where the discs are being inserted. You could add another loop:
Dim tempFolder
Set tempFolder = fso.GetFolder("C:\AutoRestore\")
Do While MsgBox("Please insert disc and click OK. When all discs have been inserted, click Cancel", vbOKCancel, "Auto Restore") = vbOK
For Each file In folder.Files
If InStr(1, file.Name, ".mrimg") > 0 Then
' Copy file to Temp folder
fso.CopyFile file.Path, tempFolder.Path & "\", True
End If
Next
Loop
After this, you should have all the mrimg files in the tempFolder location. I am not familiar with the parameters the Marcium command expects but this is where you would specify the new folder:
objShell.run("""%ProgramFiles%\macrium\diskrestore.exe""" & tempFolder.Path & "\" & file.Name & " -r -g -u --targetnum 0 --reboot --eject",1,false)

VBScript Create puzzle by splitting document into multiple documents that cannot be read separately

For a scavenger hunt I wanted to give my nephews 4 parts of the same letter that they would have to combine to read. I couldn't find anything online to use quickly, so I wrote one. I will updated with better code if you have some ideas.
'****************** Change things here ****************
'Change the number in perenthesis to set the number of files
Dim Letters(4)
'Set the original filename here:
originalFile = "Letter.txt"
'Set a letter to use as a syncronizer in addition to punctuation and line breaks
charSync = asc("o")
'*********************************************************
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(originalFile , 1)
Do Until objFile.AtEndOfStream
strCharacters = objFile.Read(1)
Randomize
selLetter = Int((Ubound(Letters))*Rnd+1)
If (asc(strCharacters) < 46) or (asc(strCharacters) = charSync) then
for i = 1 to Ubound(Letters)
Letters(i) = Letters(i) & strCharacters
next
else
for i = 1 to Ubound(Letters)
if i = selLetter then
Letters(i) = Letters(i) & strCharacters
else
Letters(i) = Letters(i) & " "
end if
next
end if
Loop
For n = 1 to Ubound(Letters)
outFileName = replace(originalFile ,".",n & ".")
Set objFile = objFSO.CreateTextFile(outFileName,True)
objFile.Write Letters(n)
objFile.Close
next
Set objFSO=Nothing
Usage:
Create a text file you want to split up randomly
Edit the script for the following:
Set the number of documents to split it into
Set the file name of the file to update
Select a synch character if you want to
Run the script and it will create numbered files
Use equal character spacing font like system to read by holding up to light
'****************** Change things here ****************
'Change the number in perenthesis to set the number of files
Dim Letters(4)
'Set the original filename here:
originalFile = "Letter.txt"
'Set a letter to use as a syncronizer in addition to punctuation and line breaks
charSync = asc("o")
'*********************************************************
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(originalFile , 1)
Do Until objFile.AtEndOfStream
strCharacters = objFile.Read(1)
'uncomment next 2 comments to simplify and change only once per word:
'If strCharacters = " " then
Randomize
selLetter = Int((Ubound(Letters))*Rnd+1)
'end if
If (asc(strCharacters) < 46) or (asc(strCharacters) = charSync) then
for i = 1 to Ubound(Letters)
Letters(i) = Letters(i) & strCharacters
next
else
for i = 1 to Ubound(Letters)
if i = selLetter then
Letters(i) = Letters(i) & strCharacters
else
Letters(i) = Letters(i) & " "
end if
next
end if
Loop
For n = 1 to Ubound(Letters)
outFileName = replace(originalFile ,".",n & ".")
Set objFile = objFSO.CreateTextFile(outFileName,True)
objFile.Write Letters(n)
objFile.Close
next
Set objFSO=Nothing
Usage:
Create a text file you want to split up randomly
Edit the script for the following:
Set the number of documents to split it into
Set the file name of the file to update
Select a synch character if you want to
Run the script and it will create numbered files
Use equal character spacing font like system to read by holding up to light

Delete Files After Filename - vbscript

Basically I am trying to write a script to delete files after a certain filename, so based on the below file list
FILE_000001_FULL.ZIP
FILE_000002_FULL.ZIP
FILE_000003_FULL.ZIP
FILE_000004_FULL.ZIP
FILE_000005_FULL.ZIP
FILE_000006_DELTA.ZIP
FILE_000007_DELTA.ZIP
FILE_000008_FULL.ZIP
Everything up until FILE_000005_FULL.ZIP would be deleted. The files are created using a tool and will be sorted by file name, so highest number first. Basically need the 2 latest FULL files kept and the DELTA's (if any) between them. I hope that makes sense.
So far, this is what I have, but just loops constantly, not just until it finds the 2 latest fulls.
Dim fso, folder, files, ToDel, sfolder
Set fso = CreateObject("Scripting.FileSystemObject")
sFolder = ("C:\MDS")
Set ToDel = fso.CreateTextFile ("C:\MDS\FileList.txt", True)
Set folder = fso.GetFolder(sFolder)
set files = folder.files
For each folderIDX In files
ToDel.WriteLine(folderidx.Name)
Next
ToDel.close
Dim arrFileLines()
i = 0
Set ObjFile = FSO.OpenTextFile("C:\MDS\FileList.txt", 1)
Do Until objFile.AtEndOfStream
Redim Preserve arrFileLines(i)
arrFileLines(i) = objFile.ReadLine
i = i + 1
Loop
ObjFile.Close
s = 0
Do While s < 2
For l = Ubound(arrFileLines) to LBound(arrFileLines) Step -1
For Each strLine in arrFileLines
IF InStr(strLine, "FULL") <> 0 Then
wscript.echo "Found Full!!!!"
wscript.echo strLine, s
s = S + 1
End If
Next
Next
LooP
My thoughts was to delete the lines from the text file, then use this text file to delete the files from the directory.
Hopefully that all makes sense and someone can pass some advice on!
You should be able to do this with two iterations through your folder and without the need/use of a text file. During the first pass, record the numbers assigned to the two latest FULL's. Then, in your second pass, delete any files that are less than your second-highest FULL.
Here's how it might look:
' First pass: Find the two latest FULLs...
For Each File In FSO.GetFolder("c:\mds").Files
' Is this a FULL?
If Right(File.Name, 8) = "FULL.ZIP" Then
' Get the numeric value from the file name (6 digits starting as pos 6)...
intNum = CLng(Mid(File.Name, 6, 6))
' Maintain the two latest FULLs...
If intNum > intMax1 Then
intMax2 = intMax1
intMax1 = intNum
ElseIf intNum > intMax2 Then
intMax2 = intNum
End If
End If
Next
' Second pass: Delete anything prior to the second-latest FULL...
For Each File In FSO.GetFolder("c:\mds").Files
intNum = CLng(Mid(File.Name, 6, 6))
If intNum < intMax2 Then File.Delete
Next

Isolating numbers in folder names

I have created a script, out of snip-its found all over this site and elsewhere, to assign job numbers. It (is supposed to) search the "Jobs" directory for the highest job number, increment by 1, prompt for a customer name and job name, copy a template dir and rename it with the information provided. I know my code is messy, but it worked wonderfully...until someone put numbers in the job name (09889KM-TCM-Vadata PDX50 - POD 3). It now does it's intended job, but then runs again with the next number it finds in the job name i.e. increments 09889 to 09890 then picks up on PDX50 and tries to make a new folder 00051. I have been looking all day to find how to isolate the numbers on my own and, but as this script is in production I have no choice to beg for help. Please assist on how to isolate the first 5 digits, or make it stop after one run.
Option Explicit
Dim objFSO
Dim objNewFolder
Dim fs
Dim MainFolder
DIM JobNumber, nJobNumber, EmplInit, CustName, JobName
Dim fldr, LastName, LastJob, r, x, y
Dim OldFolder, sFile
'Find Highest Job Number Folder
Set fs = CreateObject("Scripting.FileSystemObject")
Set MainFolder = fs.GetFolder("C:\Test\")
For Each fldr In MainFolder.SubFolders
If fldr.Name > LastName Then
LastJob = fldr.Name
LastName = fldr.Name
End If
Next
'Extract JobNumber from name and increment by 1, and format to five numbers
Set r=new regexp
r.pattern="[0-9]+"
r.global=true
x=LastJob
Set y=r.execute(x)
For each JobNumber in y
JobNumber = Right("00000" & JobNumber, 5)
nJobNumber = JobNumber + 1
nJobNumber = Right("00000" & nJobNumber, 5)
' Start recieving input
' Get initials
EmplInit = InputBox ("The last Job Number is: " & VbCrLf & Jobnumber & VbCrLf & "You have been assigned Job Number: " & VbCrLf & nJobNumber & VbCrLf & "Please Typer your initials:","Initials")
If IsEmpty(EmplInit) Then
MsgBox "Canceled"
ElseIf Len(EmplInit) = 0 Then
MsgBox "You Clicked OK but left the box blank"
Else
'Get Customer Name
CustName = InputBox ("Please enter your customer's name:","Customer Name")
If IsEmpty(EmplInit) Then
MsgBox "Canceled"
ElseIf Len(EmplInit) = 0 Then
MsgBox "You Clicked OK but left the box blank"
Else
'Get Job Name
JobName = InputBox ("Please enter your job's name:","Job Name")
If IsEmpty(EmplInit) Then
MsgBox "Canceled"
ElseIf Len(EmplInit) = 0 Then
MsgBox "You Clicked OK but left the box blank"
Else
' Create New Job Folder Name
objNewFolder = ("C:\Test\" & nJobNumber & EmplInit & "-" & CustName & "-" & JobName)
'Create the File System Object
Set objFSO = CreateObject ("Scripting.FileSystemObject")
'Get the folder we want to copy from
OldFolder = "C:\Test\00AA-Working Edit - Folder Template\"
'Check if new folder exists, if not then create it.
If objFSO.FolderExists (objNewFolder) then
WScript.Echo "The Destination Folder " & objNewFolder & " already exists"
Else
WScript.Echo "The Destination Folder " & objNewFolder & " will be created."
Set objNewFolder = objFSO.CreateFolder (objNewFolder)
End If
'Copy source folders to new folder
objFSO.CopyFolder "C:\Test\00AA-Working Edit - Folder Template\*" , (objNewFolder & "\")
'Copy any files in the source root to new location
For Each sFile In objFSO.GetFolder(OldFolder).Files
If Not objFSO.FileExists(objNewFolder & "\" & objFSO.GetFileName(sFile)) Then
objFSO.GetFile(sFile).Copy objNewFolder & "\" & objFSO.GetFileName(sFile),True
End If
Next
End If
End If
End If
Next
Change this:
'Extract JobNumber from name and increment by 1, and format to five numbers
Set r=new regexp
r.pattern="[0-9]+"
r.global=true
x=LastJob
To this:
'Extract JobNumber from name and increment by 1, and format to five numbers
Set r=new regexp
r.pattern="[0-9]+"
r.global=true
x=Left(LastJob,5)
You're just changing one line (the last).
I don't think you need the regular expression. In fact, it sounds like that's part of your problem because in addition to finding the first 5 digits, it's finding any digits within the folder name and operating on those as well.
After you determine LastJob, just do this:
x = Left(LastJob, 5)
If IsNumeric(x) Then
nJobNumber = Right("00000" & x + 1, 5)
' Start your InputBox() prompts...
End If
r.pattern="^[0-9]+"
To avoid more changes in code, just indicate in the regexp that the pattern should be at the start of line.

Resources