VBS batch modify file, bat batch file call to execute VBS, and print the return value in CMD window (VBS running result)

Time:2019-11-13

The sample code (t.vbs) is as follows:

Copy codeThe code is as follows:
Set fso=Wscript.CreateObject(“Scripting.FileSystemObject”)
flrName=”D:\Workspace\src\” ‘dir that you need deal with
count=0 ‘get the count of modified files
function Traversal(dir)
set flr=fso.getfolder(dir)
set fs=flr.files
findstr1=”[assembly: SecurityTransparent]” ‘find string that need to be replaced
findstr2=replace(findstr1,” “,””) ‘becasuse there is space char in findstr,so add this findstr2
replaceStr=”[assembly: AllowPartiallyTrustedCallers()]” ‘destination string in replace

for each f in fs
if lcase(f.name)=”assemblyinfo.cs” then
set findf=fso.opentextfile(f)
do while findf.atendofstream=false
d=f.datelastmodified ‘get modified datetime of current file
alltext=findf.readall

if(InStr(alltext,findstr1) > 0 ) then
s=replace(alltext,findstr1, replaceStr)
count=count+1
findf.close()
‘If no findstr2, delete the following elseif block
elseif(InStr(alltext,findstr2) > 0) then
s=replace(alltext,findstr2, replaceStr)
count=count+1
findf.close()

else
findf.close()
exit do
end if

set r=fso.opentextfile(f, 2, true)
r.write s

d2=f.datelastmodified

if d2>=d then exit do
loop

end if
next

set fs=flr.subfolders
for each f in fs
Traversal(f.path)
next

end function

Traversal(flrName)
‘msgbox (“Done! “& count & ” files were modified successfully.”)
wscript.echo “Done! “& count & ” files were modified successfully.” ‘value popup by “wscript.echo” can be received by .bat easily

Wscript.quit count ‘this variable “count” in order to get a return value by %ErrorLevel%

The above operation only performs the steps of processing files
If you don’t need to extract the running results, you can run the VBS file directly in the batch or main vbs script.

If you call the vbs script in bat and want to print out the prompt information
There are two ways to do this:
1. Add the following code to bat

Copy codeThe code is as follows:
@echo off
for /f “delims=” %%a in (‘cscript //nologo c:\t.vbs’) do (
set ScriptOut=%%a)
echo Result: %ScriptOut%

The format of the echo print string above is defined according to your needs. The file directory of C: \ t.vbs is changed to your VBS file directory.

2. Add in bat

Copy codeThe code is as follows:
@echo off
cscript //nologo c:\t.vbs
echo —–Modify %ErrorLevel% “AssemblyInfo.cs” files successfully.—–

The above echo text format defines% errorlevel% according to your own needs to get the value of count at the end of the above sample VBS file. Also, you need to modify the directory of the VBS file C: \ t.vbs