vbscript need to detect drive letter and ask for user input - windows

I already have the script that ask user input to install the file "install1.exe" to "install6.exe" with default drive letter path D:\, I have another drive can get the drive letter like "C:", not sure how to integrate
First I need to have drive letter check to confirm the computer have drive D physical local disk (not cdrom), if yes prompt user confirm to proceed
or user can click no to enter a drive letter, the drive letter also need to update on current install script {D}:\temp\install1.exe
drive letter script
Dim query
Dim objWMI
Dim diskDrives
Dim diskDrive
Dim partitions
Dim partition ' will contain the drive & partition numbers
Dim logicalDisks
Dim logicalDisk ' will contain the drive letter
Set objWMI = GetObject("winmgmts:\\.\root\cimv2")
Set diskDrives = objWMI.ExecQuery("SELECT * FROM Win32_DiskDrive") ' First get out the physical drives
For Each diskDrive In diskDrives
query = "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + diskDrive.DeviceID + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition" ' link the
physical drives to the partitions
Set partitions = objWMI.ExecQuery(query)
For Each partition In partitions
query = "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition.DeviceID + "'} WHERE AssocClass = Win32_LogicalDiskToPartition" ' link
the partitions to the logical disks
Set logicalDisks = objWMI.ExecQuery (query)
For Each logicalDisk In logicalDisks
' Wscript.Echo logicalDisk.DeviceID & " - " & partition.Caption
Wscript.Echo logicalDisk.DeviceID
'else
Next
Next
Next
Install script
Dim objShell
Dim Message, result
Dim Title, Text1, Text2
' Define dialog box variables.
Message = "Please enter a path"
Title = "Install Started"
Text1 = "Install Cancelled"
Text2 = "You entered value is incorrect, please select from 1,2,3,4,5 or 6" & vbCrLf
result = InputBox("Please select the by number"& Chr(13) & "A" & Chr(13) & "B" & Chr(13) & "C" & Chr(13) & "D" & Chr(13) & "E" & Chr(13) & "F", Title, "Please enter the number", 100, 100)
Set objShell = WScript.CreateObject( "WScript.Shell" )
' Evaluate the user input.
If result = "" Then ' Canceled by the user
WScript.Echo Text1
ElseIf result = "1" Then
objShell.Run("7z.exe x temp.7z -oD:\ -bd -y")
wscript.sleep (3000)
objShell.Run("D:\temp\install1.exe")
wscript.sleep (150000)
wScript.Echo "install Completed"
ElseIf result = "2" Then
......
......
......
Else
WScript.Echo Text2 & result
End If
wscript.quit
thank you

Related

Convert batch to VBS script

I am running this command remotely in a VBS script file. The problem I am having is that it generates a CMD window momentarily and it distracts some users. How can I run this without generating the CMD window? Preferably, I want to get the WMI data in native VBS language without using oShell.run? I rather not use CMD. Thanks.
oShell.run "cmd /c wmic logicaldisk get name,providername,description,volumename,filesystem /format:list > c:\users\%username%\drives.txt"
Or you could just use what you've already got and pass the 'hidden window' parameter to the Run command (see the second parameter of 0 below):
Dim objShell : Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "cmd /c wmic logicaldisk get name,providername,description,volumename,filesystem /format:list > c:\users\%username%\drives.txt", 0, true
Set objShell = Nothing
You can give a try for this code in pure vbscript :
Option Explicit
Dim Ws,ReportFile,strHomeFolder
Set Ws = CreateObject("WScript.Shell")
strHomeFolder = Ws.ExpandEnvironmentStrings("%USERPROFILE%")
ReportFile = strHomeFolder & "\drives.txt"
'MsgBox GetDrives_Information
Call WriteReport(GetDrives_Information,ReportFile)
'-------------------------------------------------------
Function GetDrives_Information()
Dim oFSO,report,objWMIService,objLogicalDisk
Set oFSO = CreateObject("Scripting.FileSystemObject")
Dim oDrives
Set oDrives = oFSO.Drives
Dim oDrive
Dim strLectType
on error resume next
For Each oDrive in oDrives
If oDrive.IsReady Then
Select Case oDrive.DriveType
Case 0: strLectType = "Unknown"
Case 1: strLectType = "Amovible (USB)"
Case 2: strLectType = "Fixe (Hard Drive)"
Case 3: strLectType = "Network"
Case 4: strLectType = "CD-Rom"
Case 5: strLectType = "Virtuel"
End Select
report = report & "- Drive letter: " & oDrive.DriveLetter & vbCrLf
report = report & "- serial number: " & oDrive.SerialNumber & vbCrLf
report = report & "- Drive Type: " & oDrive.strLectType & vbCrLf
If (oDrive.FileSystem <> "") Then
report = report & "- File system used : " & oDrive.FileSystem & vbCrLf
End If
Set objWMIService = GetObject("winmgmts:")
Set objLogicalDisk = objWMIService.Get("Win32_LogicalDisk.DeviceID='" & oDrive.DriveLetter & ":'")
report = report & "- There is " & objLogicalDisk.FreeSpace /1024\1024+1 & " Mo remaining space on this drive / disk" & vbCrLf
report = report & "- There is " & objLogicalDisk.Size /1024\1024+1 & " Mo total space on this drive / disk" & vbCrLf
End If
report = report & vbCrLf
Next
GetDrives_Information = report
End Function
'-------------------------------------------------------
Sub WriteReport(strText,ReportFile)
Dim fs,ts
Const ForWriting = 2
Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.OpenTextFile(ReportFile,ForWriting,True)
ts.WriteLine strText
ts.Close
End Sub
'------------------------------------------------------

Code checks one drive for three different drive letters

So I have created a code that reads the following text file:
Diskspace C:
Diskspace D:
Diskspace E:
Memory
CPU
And check usage for each type of "hardware" listed.
I only have a disk C: on my computer, so how can I put an error message for any disk that doesn't work?
What happens in my script now is since I have "On Error Resume Next", my code checks whatever disk it can analyze, and inputs that answer (aka disk C:) for each disk. For example, in my wscript.echo box, it says
Disk C: is 93.4% free.
Disk D: is 93.4% free.
Disk E: is 93.4% free.
I know that this is wrong.
On Error Resume Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objReadFile = objFSO.OpenTextFile("M:\vbscripts\ServerHealthCheck_Control.txt")
message = ""
Do While objReadFile.AtEndOfStream <> True
strLine = objReadFile.ReadLine
If Left(strLine, 1) = "D" then
letter = Mid(strLine, 11, 2)
Set fso = CreateObject("Scripting.FileSystemObject")
Set drive = fso.GetDrive(letter)
totalSpace = drive.TotalSize / 1024
freeSpace = drive.AvailableSpace / 1024
percentFree = freeSpace / totalSpace
number = FormatNumber(percentFree*100, 2)
'WARNING_MESSAGE = Mid(strLine, 14, 2)
'ERROR_MESSAGE = Mid(strLine, 17, 2)
message = message & "Drive " & letter & " is " & number & "% free." & vbCrlf
Elseif Left(strLine, 1) = "M" then
Const CONVERT = 1048576 ' This is total bytes in 1 MB.
Const strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colSettings = objWMIService.ExecQuery ("Select * from Win32_OperatingSystem")
For Each objOperatingSystem in colSettings
intFreeMem = objOperatingSystem.FreePhysicalMemory / CONVERT
intTotalMem = objOperatingSystem.TotalVisibleMemorySize / CONVERT
Memory = intFreeMem / intTotalMem * 100
message = message & "Memory is " & FormatNumber(Memory,2) & "% free." & vbCrlf
Next
Elseif Left(strLine, 1) = "C" then
Set objWMIService = GetObject("winmgmts:\\localhost\root\CIMV2")
Set CPUInfo = objWMIService.ExecQuery("SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor",,48)
For Each Item in CPUInfo
If Item.Name = "_Total" Then
message = message & "Total CPU usage is " & Item.PercentProcessorTime & "%."
End If
Next
End If
Loop
Wscript.Echo message
EDIT: I have tried the following but it doesn't seem to work:
If fso.GetDrive(letter) = error then
message = message & "The drive " & letter & " cannot be read."
Elseif fso.GetDrive(letter) <> error then
totalSpace = drive.TotalSize / 1024
freeSpace = drive.AvailableSpace / 1024
percentFree = freeSpace / totalSpace
number = FormatNumber(percentFree*100, 2)
message = message & "Drive " & letter & " is " & number & "% free." & vbCrlf
End If
It displays that E: is an error, but disk D still copies disk C.
Replace the EVIL global OERN with a strictly local one (a call of a Sub/Function containing the risky operation(s)). As in:
Option Explicit
Dim goFS : Set goFS= CreateObject("Scripting.FileSystemObject")
Function RiskyGetDrive(sDL)
' maybe lots of lines here, immediate exit on first error
Set RiskyGetDrive = goFS.GetDrive(sDL) ' could be unavailable
Dim dummy : dummy = RiskyGetDrive.TotalSize ' could be not ready
End Function
Dim sDL, oDrv, aErr
For Each sDL in Split("C D E Q")
' error hiding for just one risky operation and copy of (possible) error data
On Error Resume Next
Set oDrv = RiskyGetDrive(sDL)
aErr = Array(Err.Number, Err.Description)
On Error GoTo 0
If aErr(0) Then
WScript.Echo sDL, "Diag:", aErr(0), aErr(1)
Else
'not needed, if "not ready" is provoked in function
'If Not oDrv.IsReady Then
' WScript.Echo sDL, "Diag:", "not ready"
'Else
' WScript.Echo sDL, "Info:", oDrv.TotalSize / 1024
'End If
WScript.Echo sDL, "Info:", oDrv.TotalSize / 1024
End If
Next
output:
cscript 41173138.vbs
C Info: 41929616
D Diag: 71 Disk not ready
E Info: 227784528
Q Diag: 68 Device unavailable
You can get help on WMI by using the command line utility wmic /? and wmic logicaldisk get /?
wmic logicaldisk get caption,freespace
outputs the freespace on ALL drives. In VBScript the above becomes
Set colSettings = objWMIService.ExecQuery ("Select * from Win32_LogicalDisk")
For Each objdisk in colSettings
wscript.echo objdisk.caption & " " & objdisk.freespace
Next
You can use a where clause in both VBScript or WMIC.
wmic logicaldisk where (caption="C:" or caption="D:" or caption="E:") get caption,freespace

VBScript issue with values in a table

I have this code to build a table and send it via e-mail to business. They want to know, on a daily basis, how many files were transferred from a Source to a Destination, and if there's a difference in the number of files (possible failed/corrupted transfers). All this by folder.
The problem is that this code somehow misses the row of the Number of Missing Files in the Destination folder. It seems like if it were attributing the row in a random manner. The image below shows that even though the folder 3 is complete, it does say there is 1 missing file, and the folder 5 has 1 missing file (59 in the Source and only 58 in the Destination folder) and it states 0 missing items. What am I missing here?
The code is:
' >>> init a Windows Shell object to run system commands
SET WshShell = WScript.CREATEOBJECT("WScript.Shell")
' >>> load email Class code
WDIR = "D:\Kofax_Scripts"
SET objFSO = CreateObject("Scripting.FileSystemObject")
SET mailObjectFile = objFSO.OpenTextFile( WDIR & "\email.vbs", 1)
Execute mailObjectFile.ReadAll()
' >>> TEST passed arguments
If WScript.Arguments.Count = 0 Then
Wscript.echo vbCr & vbLf & "Usage is: cscript.exe //nologo Kofax_SAP_crosscheck.vbs DEV|PRD [date]" & vbCrLf
Wscript.echo "If date is not given, script uses system current date. To run this script for other dates, you must pass it in format YYYY-MM-DD"
wscript.quit
End If
If WScript.Arguments.Item(0) = "DEV" Then
Wscript.echo "Running in DEV..."
ElseIf WScript.Arguments.Item(0) = "PRD" Then
Wscript.echo "Running in PRD..."
Else
Wscript.echo vbCr & vbLf & "Environment parameter is wrong! Possible choices: DEV|PRD"
wscript.quit
End If
' >>> Get today's date
t1=Now()
Wscript.echo "starting at: " & t1
' >>> Set date to use for the files' date crosscheck
Dim date_cross_check
If WScript.Arguments.Count = 2 Then
date_cross_check = CDate(WScript.Arguments.Item(1))
Else
date_cross_check = t1
End If
' >>> compose date string from the files pathname to be checked
ano = Year(date_cross_check)
mes = Month(date_cross_check)
dia = Day(date_cross_check)
date_cross_check_str = ano & "/" & mes & "/" & dia
' Set lists of Folders to cross-check
Set KofaxFolders = CreateObject("Scripting.Dictionary")
Set SapFolders = CreateObject("Scripting.Dictionary")
KofaxFolders.Add "AMOS", CreateObject("Scripting.Dictionary")
KofaxFolders.Add "bomdia", CreateObject("Scripting.Dictionary")
KofaxFolders.Add "cockpit", CreateObject("Scripting.Dictionary")
KofaxFolders.Add "irreg", CreateObject("Scripting.Dictionary")
KofaxFolders.Add "miro", CreateObject("Scripting.Dictionary")
KofaxFolders.Add "BSP", CreateObject("Scripting.Dictionary")
SapFolders.Add "AMOS", CreateObject("Scripting.Dictionary")
SapFolders.Add "bomdia", CreateObject("Scripting.Dictionary")
SapFolders.Add "cockpit", CreateObject("Scripting.Dictionary")
SapFolders.Add "irreg", CreateObject("Scripting.Dictionary")
SapFolders.Add "miro", CreateObject("Scripting.Dictionary")
SapFolders.Add "BSP", CreateObject("Scripting.Dictionary")
' init dictionaries
For each key in KofaxFolders
KofaxFolders(key).Add "files", CreateObject("Scripting.Dictionary")
KofaxFolders(key).Add "count", 0
Next
For each key in SapFolders
SapFolders(key).Add "files", CreateObject("Scripting.Dictionary")
SapFolders(key).Add "missing", 0
SapFolders(key).Add "count", 0
Next
' init File System Object
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Loop on KofaxFolders to fill contents folders
for each key in KofaxFolders
fldr = "D:\Projetos\EXPORT\" & key &"\Save\"& ano &"\"& mes &"\"& dia
If (objFSO.FolderExists(fldr)) Then
Set objFolder = objFSO.GetFolder(fldr)
For Each objFile In objFolder.Files
' Don't consider garbage files like Thumbs.db
If ( objFile.name <> "Thumbs.db" ) Then
' Wscript.echo "Folder : " & key & "Filename: " & objFile.name & ", size (bytes): " & objFile.size
KofaxFolders(key)("files").Add objFile.name, objFile.size
KofaxFolders(key)("count") = KofaxFolders(key)("count") + 1
End If
Next
End If
next
' Loop on SapFolders to fill contents folders
for each key in SapFolders
Set objFolder = objFSO.GetFolder("\\iftpv01\TPP\transdata\InB\OCRSave\Save"&key)
'WScript.Echo "Folder : " & key
For Each objFile In objFolder.Files
'Wscript.echo "Folder : " & key & "Filename: " & objFile.name & ", size (bytes): " & objFile.size
' Check only SAP files with last Modified Date equal to specified date
' --------------------------------------------------------------------
If ( DateDiff("d",objFile.DateLastModified, CDate(date_cross_check)) = 0 )Then
' Don't consider garbage files like Thumbs.db
If ( objFile.name <> "Thumbs.db" ) Then
SapFolders(key)("files").Add objFile.name, objFile.size
SapFolders(key)("count") = SapFolders(key)("count") + 1
End If
End If
Next
next
' ------------------------'
' Start new empty log file'
' ------------------------'
Dim log_file
log_file = WDIR & "\tmp\kofax_sap_crosscheck.log"
Set objLogFile = objFSO.CreateTextFile(log_file,True)
objLogFile.Close
' open file in write mode
Set objLogFile = objFSO.OpenTextFile(log_file, 2)
' Loop on KofaxFolders Contents and check if file exists in SAP structure
For each key in KofaxFolders
For each file in KofaxFolders(key)("files")
If ( NOT SapFolders(key)("files").Exists(file) ) Then
objLogFile.WriteLine("file " & file & " is missing from InB SAP folder "&key)
SapFolders(key)("missing") = SapFolders(key)("missing") + 1
Else
' If file size is different between Kofax and SAP, this may be due to corrupt transfer
If SapFolders(key)("files")(file) <> KofaxFolders(key)("files")(file) Then
objLogFile.WriteLine("file " & file & " has not same size in SAP and Kofax " & key &" Folders!!! Kofax size: " _
& KofaxFolders(key)("files")(file) & "| SAP size: " _
& SapFolders(key)("files")(file) _
)
SapFolders(key)("missing") = SapFolders(key)("missing") + 1
End If
End If
Next
Next
' close log file
objLogFile.Close
' compute execution time
exec_time = datediff("s",t1,Now)
' Global missing count
Dim missing_files : missing_files = 0
For each key in SapFolders
missing_files = missing_files + SapFolders(key)("missing")
Next
' Build summary HTML table according to "missing_files" count
Dim rep_table : rep_table = ""
if ( missing_files > 0 )Then
rep_table = "<table border=""1""><tr><th>Folder</th><th>Nr of files Source</th><th>Nr of files Dest</th><th>Nr of Files missing Dest</th></tr>"
For each key in SapFolders
rep_table = rep_table & "<tr><td>" & key & "</td><td align=""right"">" & KofaxFolders(key)("count") &"</td><td align=""right"">" & SapFolders(key)("count") & "</td>"
if ( SapFolders(key)("missing") > 0 ) Then
rep_table = rep_table & "<td align=""right"" bgcolor=""#FF0000"">"
Else
rep_table = rep_table & "<td align=""right"">"
End If
rep_table = rep_table & SapFolders(key)("missing") &"</td></tr>"
Next
Else
rep_table = "<table border=""1""><tr><th>Pasta</th><th>Nº ficheiros no Kofax</th><th>Nº ficheiros no SAP</th></tr>"
For each key in SapFolders
rep_table = rep_table & "<tr><td>" & key & "</td><td align=""right"">" & KofaxFolders(key)("count") &"</td><td align=""right"">" & SapFolders(key)("count") & "</td></tr>"
Next
End If
rep_table = rep_table & "</table>"
I am not 100% sure about what is happening here, but I think that the issue is that SapFolders is a dictionary and you are using the line
For each key in SapFolders
to iterate over it when creating the table. The order of keys in such an iteration is (essentially) random. In your case, it isn't true that the loop iterate over the keys "AMOS", "bomdia", "cockpit", "irreg", "miro", "BSP" in that order.
What you could do is to create an array:
keys = Array("AMOS", "bomdia", "cockpit", "irreg", "miro", "BSP")
and replace every loop which begins
For each key in SapFolders
by
For i = 0 to UBound(keys)
key = keys(i)
(and maybe do a similar move for iterations involving KofaxFolders).
This will guarantee that you know the order with which you are populating the report table.

How to add a mapped network drive via VBS?

I'm having some issues with my vbs script. It will add only the F drive and not add the G driver after it. What am I doing wrong?
'## This is for network drives
Set objNetwork = CreateObject("WScript.Network")
objNetwork.RemoveNetworkDrive "F:", True, True
'## for adding
Set objNetwork = CreateObject("WScript.Network")
objNetwork.MapNetworkDrive "F:" , "\\myserver\share1"
objNetwork.MapNetworkDrive "G:" , "\\myserver\share2"
MapDrive.vbs
VBScript to Map a Drive letter to a network file share (non-persistent).
This script is designed for reliability above speed, so it will reconnect at every login.
It accounts for 'remembered' connections including those to a file share that no longer exists or which is off-line.
This is a good approach for machines that are not always connected to the domain e.g. Laptops.
Windows XP will not map a 'remembered' connection to a different server unless you first unmap & unremember the existing connection, this applies even if the old connection path is currently disconnected.
For each drive letter there are several possible states, that may have to be dealt with by the script:
- Remembered (persistent connection) / Not Remembered
- Already Connected / Connected to the wrong network share / Not Connected.
This script will remove any existing Drive Map, before connecting to the correct file share.
' Map a network drive
' Usage
' cscript MapDrive.vbs drive fileshare //NoLogo
' cscript MapDrive.vbs H: \\MyServer\MyShare //NoLogo
'
' This script will remove any existing drive map to the same drive letter
' including persistent or remembered connections (Q303209)
Option Explicit
Dim objNetwork, objDrives, objReg, i
Dim strLocalDrive, strRemoteShare, strShareConnected, strMessage
Dim bolFoundExisting, bolFoundRemembered
Const HKCU = &H80000001
' Check both parameters have been passed
If WScript.Arguments.Count < 2 Then
wscript.echo "Usage: cscript MapDrive.vbs drive fileshare //NoLogo"
WScript.Quit(1)
End If
strLocalDrive = UCase(Left(WScript.Arguments.Item(0), 2))
strRemoteShare = WScript.Arguments.Item(1)
bolFoundExisting = False
' Check parameters passed make sense
If Right(strLocalDrive, 1) <> ":" OR Left(strRemoteShare, 2) <> "\\" Then
wscript.echo "Usage: cscript MapDrive.vbs drive fileshare //NoLogo"
WScript.Quit(1)
End If
wscript.echo " - Mapping: " + strLocalDrive + " to " + strRemoteShare
Set objNetwork = WScript.CreateObject("WScript.Network")
' Loop through the network drive connections and disconnect any that match strLocalDrive
Set objDrives = objNetwork.EnumNetworkDrives
If objDrives.Count > 0 Then
For i = 0 To objDrives.Count-1 Step 2
If objDrives.Item(i) = strLocalDrive Then
strShareConnected = objDrives.Item(i+1)
objNetwork.RemoveNetworkDrive strLocalDrive, True, True
i=objDrives.Count-1
bolFoundExisting = True
End If
Next
End If
' If there's a remembered location (persistent mapping) delete the associated HKCU registry key
If bolFoundExisting <> True Then
Set objReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
objReg.GetStringValue HKCU, "Network\" & Left(strLocalDrive, 1), "RemotePath", strShareConnected
If strShareConnected <> "" Then
objReg.DeleteKey HKCU, "Network\" & Left(strLocalDrive, 1)
Set objReg = Nothing
bolFoundRemembered = True
End If
End If
'Now actually do the drive map (not persistent)
Err.Clear
On Error Resume Next
objNetwork.MapNetworkDrive strLocalDrive, strRemoteShare, False
'Error traps
If Err <> 0 Then
Select Case Err.Number
Case -2147023694
'Persistent connection so try a second time
On Error Goto 0
objNetwork.RemoveNetworkDrive strLocalDrive, True, True
objNetwork.MapNetworkDrive strLocalDrive, strRemoteShare, False
WScript.Echo "Second attempt to map drive " & strLocalDrive & " to " & strRemoteShare
Case Else
On Error GoTo 0
WScript.Echo " - ERROR: Failed to map drive " & strLocalDrive & " to " & strRemoteShare
End Select
Err.Clear
End If
Set objNetwork = Nothing
From http://ss64.com/vb/syntax-mapdrive.html
I've done this before like this:
dim objNet, strLocal, strPath, fso
Set fso = WScript.CreateObject("Scripting.FileSystemObject")
Set objNet = WScript.CreateObject("WScript.Network")
'Name the drives and their paths
strLocal = Array("H:","M:")
strPath = Array("\\Full\Path\Number1", _
\\Full\Path\Number2")
'Loop to check if they are mapped, map it if they are not
For i = LBound(strLocal) To UBound(strLocal)
If fso.FolderExists(strLocal(i)) = True Then
wscript.echo(strLocal(i) & " Mapped")
Else
objNet.MapNetworkDrive strLocal(i), strPath(i), False
wscript.echo(strLocal(i) & " Re-mapped")
End If
Next
'Wrap up the script
WScript.Echo("")
WScript.Echo("Mapping Completed")
WScript.Sleep(2000)
'Keep the command prompt open long enough to see that it is completed
Set fso=Nothing
Set objNet=Nothing
Essentially, it checks to see if the drive is mapped already, and if not, then it will map it. I added this to my startup folder because I keep getting my corp network drives to lose connection when I reboot.

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