VBS to Rename File via Send To Menu - file

Every day I have to rename files to replace spaces with dashes before I can send them to our machines (a few of our machines don't read spaces in file names but our file naming conventions have spaces, a conflict of interest I know).
Sometimes it's one file others it's a half dozen so my approach is to use the Windows Send To menu to send selected files to the script.
I've gotten as far as renaming the strings but the actual move function says path not found when I get to the fso.movefile function.
Here's what I have so far.
Set objArgs = WScript.Arguments
Dim Fso
Set Fso = WScript.CreateObject("Scripting.FileSystemObject")
'Cycle through files
For I = 0 to objArgs.Count - 1
' Assign array entry to variable
t = objArgs(I)
' Parse variable to replace spaces with dashes
s = Replace(t, " ", "-")
' Let me know how I did
WScript.Echo t & vbcrlf & s
'Move 'em
fso.movefile t, s
Next
Any help will be greatly appreciated.

So my problem was the folder I was in had spaces too. So my code was trying to rename to a folder that didn't exist.
Once I parsed the file name out of the path and re-grouped the modified file name it worked great. Code below.
Dim t ' original file and path
Dim s ' file name only with spaces
Dim u ' new file name without spaces
Dim v ' path only
Dim obj
Set objArgs = WScript.Arguments
set obj = WScript.CreateObject("Scripting.FileSystemObject")
'Cycle through files
For I = 0 to objArgs.Count - 1
' Assign array entry to variable
t = objArgs(I)
' Parse file name from path
s = Right(t, Len(t) - InStrRev(t, "\"))
' Remove file name from path
v = left(t, InStrRev(t, "\"))
' Parse variable to replace spaces with dashes
u = Replace(s, " ", "-")
' ' Let me know how I did
' WScript.Echo "Was(t): " & t & vbcrlf & "Is(s): " & s & vbcrlf & "Path: " & v
'Move 'em
obj.movefile t, v & u
Next

Related

Display text file using MsgBox

I have multiple files with names:
c123we_1014_A1_45333
c123we_1014_A2_45333
c123we_1014_A3_45333
What I need is to get only the third parameter and display it using a message box.
What I do is I get the third parameter and write it in text file.
For Each filelog In FileList
LogFile = Split(filelog, "~")(1)
Set otf = fso.OpenTextFile("C:\Data\" & LogFile, 1)
sFile = Split(LogFile, "_")
CurStep = sFile(3)
FileNameStep = LotId & "_" & "Step"
ScriptPath = Mid(ScriptFolder, 1, Len(ScriptFolder) - 8)
If Not fso.FileExists(ScriptFolder & "\" & FileNameStep & ".txt") Then
Set ctf = fso.CreateTextFile(ScriptFolder & "\" & FileNameStep & ".txt", True)
ctf.Close
End If
Set otf = fso.OpenTextFile(ScriptFolder & "\" & FileNameStep & ".txt", 8)
otf.Writeline "Current - " & CurStep
otf.Close
Next
My text file output will be as below:
Current - A1
Current - A2
Current - A3
I am stuck at how to display the content of text file using message box.
I have also tried using array instead write it to txt file which more simpler that using txt file. My code as below:
For Each filelog In FileList
LogFile = Split(filelog, "~")(1)
Set otf = fso.OpenTextFile("C:\Data\" & LogFile, 1)
l = 0
MsgBox FileList.Count
Do While l < FileList.Count
sFile = Split(LogFile, "_")
CurStep = sFile(4)
array.Add CurStep
l = l + 1
Loop
Next
MsgBox Join(array, vbNewLine)
But got error. The error is at MsgBox Join() line:
Error: Invalid procedure call or argument
After you have written the data to your text file you can close it and then follow these steps:
A. Open the file in Read mode again and set an object reference to it:
Set objFile = fso.OpenTextFile(ScriptFolder & "\" & FileNameStep & ".txt",1)
B. Read the contents of the file using the readall() method and store it in a variable:
tempData = objFile.readAll()
C. Close the file and Display the contents using 'Msgbox'
objFile.Close
MsgBox tempData
If you want to display the data in text file, line-by-line you can use the readline() method and modify step B to:
While not fso.atEndOfStream
tempData = fso.readline()
Msgbox tempData
Wend
Edit 2: For the second part of your question:
You should not use the word "array" as a variable name as it is a keyword in vbscript. Also, you do not add elements in an array using .Add as we are talking about arrays here not arraylists.
You can replace your code with the following:
Dim intCtr: intCtr=-1
Dim tempArr()
For Each filelog in FileList
LogFile = Split(filelog, "~")(1)
Set otf = fso.OpenTextFile("C:\Data\" & LogFile, 1)
l = 0
msgbox FileList.Count
do while l < FileList.Count
intCtr=intCtr+1
sFile = Split(LogFile, "_")
CurStep = sFile(4)
Redim preserve tempArr(intCtr)
tempArr(intCtr)=CurStep
l = l + 1
Loop
next
MsgBox Join(tempArr, vbNewLine)

Remove file extension from returned list of files

I have the below code that obtains a list of txt files from a folder, I would like to remove the .txt from the returned file name, how may I achieve this?
Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "Notes"
Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
For Each objFile in colFiles
If UCase(objFSO.GetExtensionName(objFile.name)) = "TXT" Then
document.write objFile.name & "<br>"
End If
Next
This will work:
...
For Each objFile in colFiles
If UCase(objFSO.GetExtensionName(objFile.name)) = "TXT" Then
document.write Left(objFile.name, Len(objFile.name)-4) & "<br>"
End If
Next
According to the docs, Left()
Returns a specified number of characters from the left side of a string.
You just need to know how many characters to return. Since you already know that the filename ends in .txt, you can return all but the last 4 characters. Len(objFile.name) will give you the full length, and you can subtract from there.
Or if you prefer to use a function that processes a string, I coded this for my own site once. This function returns the filename without extension, provided there is a "." anywhere in the filename, of course. If not, it simply returns the input filename.
Function RemoveFileExtension(inputFileName)
IF NOT inStr(inputFileName, ".") > 0 THEN
' Period not found
strReturnvalue = inputFileName
ELSE
' Period found. Locate last
intPositionRight = 1
DO WHILE NOT inStr(right(inputFileName, intPositionRight), ".") > 0
intPositionRight = intPositionRight + 1
LOOP
strReturnvalue = left(inputFileName, len(inputFileName) - intPositionRight)
END IF
RemoveFileExtension = strReturnvalue
End Function
Then you can simply use the function, e.g. like this:
For Each objFile in colFiles
response.write RemoveFileExtension(objFile.name) & "<br>"
Next
Happy coding. :)

vbs file drag and drop a folder

I need to make a vbs file that asks for the minimum file size when you drag and drop a folder to it. It's a little wierd. But then, it should return the input as a string that will be turned into an integer. Then it should look for files that are bigger than this minimum file size(all, i guess) and list their folder(if it's in a sub-folder), name and size.
I found some stuff on the internet but I'm a bit lost
Option Explicit
Dim FolderPath, objFSO, objFolder, objFile, input, objArgs
input = InputBox("Minimum size: ")
Set objArgs = Wscript.Arguments
Set objFSO = CreateObject("Scripting.FileSystemObject")
For i = 0 to objArgs.count
on error resume next
Set objFolder = objFSO.GetFolder(objArgs(i))
If err.number <> 0 then
ProcessFile(objArgs(i))
Else
For Each file In folder.Files
ProcessFile(file.path)
Next
End if
On Error Goto 0
Next
Function ProcessFile(sFilePath)
msgbox "Now processing file: " & sFilePath
For each objFile in objFolder.Files
WScript.Echo objFile.Name, objFile.Size & "bytes" & VbCR_
& "created: " & objFile.DateCreated & VbCR_
& "modified: " & objFile.DateLastModified
Next
You've got some issues in your code. You're using folder.files but you don't have folder declared (or defined) anywhere. The only reason you're not getting an error is because you have On Error Resume Next specified. There's no need to use On Error here and it should be removed so that you can properly debug your script. Here's a starting point for you.
' Get the folder dropped onto our script...
strFolder = WScript.Arguments(0)
' Ask for minimum file size...
intMinSize = InputBox("Minimum size: ")
' Recursively check each file with the folder and its subfolders...
DoFolder strFolder
Sub DoFolder(strFolder)
' Check each file...
For Each objFile In objFSO.GetFolder(strFolder).Files
If objFile.Size >= intMinSize Then
WScript.Echo "Path: " & objFile.Path & vbCrLf & "Size: " & objFile.Size
End If
Next
' Recursively check each subfolder...
For Each objFolder In objFSO.GetFolder(strFolder).SubFolders
DoFolder objFolder.Path
Next
End Sub
This isn't a complete script. Notice I haven't declared objFSO anywhere. I haven't checked that strFolder is a valid folder or that intMinSize is actually a number. I'll leave it up to you to fill in the missing pieces. But this should get you going.

VBS Copy Files from a text file

Hiya Guys I have a text file with locations of files I'm looking for a way to read the text file and then use those locations as a source location and copy the files to a seperate destination.
I've been playing around and have seen about dynamic arrays but cant seem to understand how to put the contents of the array into variables to read as source location.
example of what I have done so far
Dim TxtFile
dim strDestinationFolder
strDestinationFolder = "\\SERVER\DESTLOGS"
TxtFile = "c:\windows\temp\SOFTWARELOG.txt"
Dim fso: Set fso = CreateObject("Scripting.FileSystemObject")
Dim f: Set f = fso.OpenTextFile(TxtFile)
Do Until f.AtEndOfStream
WScript.Echo "PSTLocation: " & f.ReadLine ; I can read each line here in the txt file
fso.CopyFile strDestinationFolder, f.REadline
Loop
I've also tried playing with, but not sure where to start though it looks the most reliable?
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile _
(TxtFile, ForReading)
Do Until objTextFile.AtEndOfStream
strNextLine = objTextFile.Readline
arrServiceList = Split(strNextLine , ",")
WScript.Echo "Server: " & arrServiceList(0)
WScript.Echo "Service: " & objTextFile
For k = 1 to UBound(arrServiceList)
WScript.Echo vbTab & "Service: " & arrServiceList(i)
Next
Loop
Any Guidance please as to what is the best way I should go about this with vbs.
Thanks
WScript.Echo "PSTLocation: " & f.ReadLine
fso.CopyFile strDestinationFolder, f.REadline
Your code echoes one line read from the file, and then tries to copy the destination folder to the next line read from the file.
If you want to do more than one thing with a line read from a file you need to assign the read line to a variable and then use that variable. Also, you need to switch the arguments of the CopyFile method. Source comes first, then destination. Plus, if you want the destination to be a folder, it needs a trailing backslash (otherwise you'd try to overwrite a folder with a file, which raises an error).
Do Until f.AtEndOfStream
line = Trim(f.ReadLine)
WScript.Echo "PSTLocation: " & line
If fso.FileExists(line) Then fso.CopyFile line, strDestinationFolder & "\"
Loop
The Trim() accounts for spurious leading/trailing spaces in the read line, and it's always a good idea to check if a file actually exists before you try to do anything with it.
Edit: For detecting an existing destination file and appending a running number to the file name try something like this:
basename = fso.GetBaseName(line)
extension = fso.GetExtensionName(line)
destinationFile = fso.BuildPath(strDestinationFolder, basename & "." & extension)
i = 1
Do While fso.FileExists(destinationFile)
filename = basename & i & "." & extension
destinationFile = fso.BuildPath(strDestinationFolder, filename)
i = i + 1
Loop
fso.CopyFile line, destinationFile

monitor last modified time for a folder using batch file

I have a folder on my workstation where files are added every minute.
I have to monitor this folder every now and then, to see if new files are being added.
In case there is no new file in this folder for say 5 min, we perform an action.
Can we use batch file for this purpose in such a way that if there is no new file added for last 5 min, an alert /pop up apears on window screen.
Also I m new to Batch .Please let me know the steps
It seems unlikely that you are going to accomplish what you want to do with purely a batch file.
However, you can do this in a relatively simple/small VB Script, that doesn't require any additional installation on the system.
'-------------------------------------------------------------
' Monitors a folder for new files and warns if they
' are not being created within a certain time period.
'-------------------------------------------------------------
Dim intMinutes: intMinutes = 5 ' minute threshold for warning of no new files
Dim strDrive: strDrive = "c:" ' drive to monitor
Dim strPath: strPath = "\\temp\\" ' path to monitor. remember to double slashes
Dim intTimer: intTimer = "2"
Dim strComputer: strComputer = "."
Dim objWMIService: Set objWMIService = GetObject( "winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2" )
Dim strQuery: strQuery = "Select * From __InstanceOperationEvent" & " Within " & intTimer & " Where Targetinstance Isa 'CIM_DataFile'" & " And TargetInstance.Drive='" & strDrive & "'" & " And TargetInstance.Path='" & strPath & "'"
Dim colEvents: Set colEvents = objWMIService. ExecNotificationQuery (strQuery)
Dim LastNew: LastNew = Now
WScript.Echo "Monitoring new file creation... Press [Ctrl]-[C] to exit"
Do
Set objEvent = colEvents.NextEvent()
Set objTargetInst = objEvent.TargetInstance
Select Case objEvent.Path_.Class
Case "__InstanceCreationEvent"
LastNew = Now
End Select
if DateDiff("n",LastNew,Now) >= intMinutes then
' put whatever actions you want in here... the following two lines are for demo purposes only
msgbox "The last new file was " & DateDiff("n",LastNew,Now) & " minute ago!",0,"No New Files"
exit do
end if
Loop
Execute this in WScript to make it not visible or CScript to show the console window.
Replace the code inside the IF block to do what you need done (notify you of the issue).

Resources