In my bat script, is it possible to access a txt file and read it line by line. The idea I'm having is to check if the line starts with an identifier word (in my case 1 or 2 stars * or **) but to do this I need to read the file line by line.
you can use vbscript
strToFind= WScript.Arguments(0)
strToFind = Replace(strToFind,"*","\*")
strFileName = WScript.Arguments(1)
Set objFS = CreateObject( "Scripting.FileSystemObject" )
Set objFile = objFS.OpenTextFile(strFileName)
Set objRE = New RegExp
objRE.IgnoreCase = False
objRE.Pattern = "^"&strToFind&".*"
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
Set Matches = objRE.Execute(strLine)
'WScript.Echo Matches.Count
For Each Match in Matches ' Iterate Matches collection.
WScript.Echo Match.Value
Next
Loop
objFile.Close
Usage:
C:\test>cscript //nologo myscript.vbs "**" file
Here's what I found: http://www.computing.net/howtos/show/batch-file-tip-reading-writing-every-line-of-a-file/61.html
Hope that helps..
CODE:
#echo off
for /f "delims=] tokens=1*" %%a in ('find /v /n "" ^<%1') do (
echo.%%b
)
Related
I wrote a vbscript to determine what are the vbscripts running in background but when I execute my script . it only opens the folder of my script not the other scripts location or folder . What should I do?? Please help
Myscript.vbs
Set objShell = CreateObject("Wscript.Shell")
strPath = Wscript.ScriptFullName
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(strPath)
strFolder = objFSO.GetParentFolderName(objFile)
strPath = "explorer.exe /e," & strFolder
objShell.Run strPath
Please help guys . I am very new to vbscript .
I have for you an old vbscript since 2015 that can tell you what vbscript is running in the background with its command line of course to get their paths and you have a possiblity to choose what vbscript you want to kill and you get in the end of the script a log file for this.
So you can give a try for this first, and i will edit and update it for any modifications in order to answer your question.
Option Explicit
Dim Titre,Copyright,fso,ws,NomFichierLog,temp,PathNomFichierLog,OutPut,Count
If AppPrevInstance() Then
MsgBox "There is an existing proceeding !" & VbCrLF & CommandLineLike(WScript.ScriptName),VbExclamation,_
"There is an existing proceeding !"
WScript.Quit
Else
Copyright = "[Hackoo "& chr(169) & " 2015]"
Set fso = CreateObject("Scripting.FileSystemObject")
Set ws = CreateObject( "Wscript.Shell" )
NomFichierLog="Killed_Process.txt"
temp = ws.ExpandEnvironmentStrings("%temp%")
PathNomFichierLog = temp & "\" & NomFichierLog
Set OutPut = fso.CreateTextFile(temp & "\" & NomFichierLog,1)
Call Find("wscript.exe")
Call Explorer(PathNomFichierLog)
End If
'***************************************************************************************************
Function Explorer(File)
Dim ws
Set ws = CreateObject("wscript.shell")
ws.run "Explorer "& File & "\",1,True
end Function
'***************************************************************************************************
Sub Find(MyProcess)
Dim colItems,objItem,Processus,Question,Msg
Titre = " Process(es) "& DblQuote(MyProcess) &" running "
Set colItems = GetObject("winmgmts:").ExecQuery("Select * from Win32_Process " _
& "Where Name like '%"& MyProcess &"%' AND NOT commandline like " & CommandLineLike(WScript.ScriptFullName) & "",,48)
Count = 0
For Each objItem in colItems
Count= Count + 1
Processus = objItem.CommandLine
Question = MsgBox ("Would do you like to kill this script : " & DblQuote(Processus) & " ?" ,VBYesNO+VbQuestion,Titre+Copyright)
If Question = VbYes then
objItem.Terminate(0)'To kill the process
OutPut.WriteLine Processus
else
Count= Count - 1 'decrementing the count of -1
End if
Next
OutPut.WriteLine String(100,"*")
If Count > 1 Then
Msg = " were killed"
Else
Msg = " was killed"
End if
OutPut.WriteLine count & Titre & Msg
OutPut.WriteLine String(100,"*") & VbCrLF
End Sub
'**************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'**************************************************************************
Function AppPrevInstance()
With GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")
With .ExecQuery("SELECT * FROM Win32_Process WHERE CommandLine LIKE " & CommandLineLike(WScript.ScriptFullName) & _
" AND CommandLine LIKE '%WScript%' OR CommandLine LIKE '%cscript%'")
AppPrevInstance = (.Count > 1)
End With
End With
End Function
'**************************************************************************
Function CommandLineLike(ProcessPath)
ProcessPath = Replace(ProcessPath, "\", "\\")
CommandLineLike = "'%" & ProcessPath & "%'"
End Function
'**************************************************************************
EDIT : Extract_CommandLine.bat
Copy and paste this code as batch file in order to extract the command line of each process.
Set ProcessNames="cmd.exe" "mshta.exe" "powershell.exe" "cscript.exe" "wscript.exe"
You can add or remove the process name from the variable ProcessNames between the double quotes.
#echo off
Title Extract CommandLine Of Running Processes by Hackoo 2020
Mode 110,10 & color 0A
Set "TmpFile=%~n0_Abs_cmdline.txt"
Set "LogFile=%~n0_cmdline.txt
If Exist "%TmpFile%" Del "%TmpFile%"
If Exist "%LogFile%" Del "%LogFile%"
Set ProcessNames="cmd.exe" "mshta.exe" "powershell.exe" "cscript.exe" "wscript.exe"
SetLocal EnableDelayedExpansion
for %%A in (%ProcessNames%) Do (
Call :GetCommandLine %%A ProcessCmd
If defined ProcessCmd (
echo !ProcessCmd!>con
echo !ProcessCmd!>>"%TmpFile%"
)
)
Timeout /T 3 /NoBreak>nul
If Exist "%TmpFile%" Call :Extract "%TmpFile%" "%LogFile%"
If Exist "%LogFile%" Start "" "%LogFile%"
If Exist "%LogFile%" Call :ExplorerIT "%LogFile%"
Exit
::---------------------------------------------------------------------------------------------------------------
:GetCommandLine <ProcessName> <ProcessCmd>
Set "ProcessCmd="
for /f "tokens=2 delims==" %%P in (
'wmic process where caption^="%~1" get commandline /format:list ^| findstr /I "%~1" ^| find /I /V "%~nx0" 2^>nul'
) do (
if not defined %2 Set "%2=%%P"
)
Exit /b
::---------------------------------------------------------------------------------------------------------------
:Extract <InputData> <OutPutData>
(
echo Data = WScript.StdIn.ReadAll
echo Data = Extract(Data,"(^?^!.*(\x22\w^)^)\b.*(\w^).*(\.ps1^|\.hta^|\.vbs^|\.vbe^|\.cmd^|\.bat^|\.lnk^)"^)
echo WScript.StdOut.WriteLine Data
echo Function Extract(Data,Pattern^)
echo Dim oRE,oMatches,Match,Line
echo set oRE = New RegExp
echo oRE.IgnoreCase = True
echo oRE.Global = True
echo oRE.Pattern = Pattern
echo set oMatches = oRE.Execute(Data^)
echo If not isEmpty(oMatches^) then
echo For Each Match in oMatches
echo Line = Line ^& chr(34^) ^& Trim(Match.Value^) ^& chr(34^) ^& vbcrlf
echo Next
echo Extract = Line
echo End if
echo End Function
)>"%tmp%\%~n0.vbs"
cscript /nologo "%tmp%\%~n0.vbs" < "%~1" > "%~2"
If Exist "%tmp%\%~n0.vbs" Del "%tmp%\%~n0.vbs"
exit /b
::-----------------------------------------------------------------------------------------------------------
:ExplorerIT <LogFile>
#For /f "delims=" %%a in ('Type "%~1"') do (
Start "SelectFile" Explorer /select,"%%~a"
)
Exit /B
::-----------------------------------------------------------------------------------------------------------
I am trying to run the following command and return the output of it using VBscript:
dir /A-d "C:\Windows\Minidump" | find /c "/"
And I have the following script but it does not work (probably because of " charachters:
Wscript.Echo runCMD("dir /A-d "C:\Windows\Minidump" | find /c "/"")
Function runCMD(strRunCmd)
Set objShell = WScript.CreateObject("WScript.Shell")
Set objExec = objShell.Exec(strRunCmd)
strOut = ""
Do While Not objExec.StdOut.AtEndOfStream
strOut = strOut & objExec.StdOut.ReadLine()
Loop
Set objShell = Nothing
Set objExec = Nothing
runCMD = strOut
End Function
Any suggestions on how to achieve this?
dir is intrinsic; you need %comspec%.
Double quotes need to be escaped by double double quotes in VBScript:
Wscript.Echo runCMD("%comspec% /c dir /A-d ""C:\Windows\Minidump"" | find /c ""/""")
I would like to check if a specific file is empty in a windows .bat file. Here is my non working script :
set dir="C:\test"
set file="%dir%\fff.txt"
cd %dir%
if %file%%~zi == 0 exit
ftp -s:"%dir%\ftp.action"
exit
Could you help me debug this please ?
Or try it with
#echo off
set "dir=C:\temp"
set "file=%dir%\a.txt"
call :CheckEmpty "%file%"
goto :eof
:CheckEmpty
if %~z1 == 0 exit
ftp -s:"%dir%\ftp.action"
goto :eof
The main difference is that I use a function call and use the %~z1, as the modifiers only works for paramters like %1, %2..%9 or for-loop parameters like %%a ...
batch solution using file compare:
type nul > blank
fc myfile blank > nul
if errorlevel 1 echo myfile is not empty
Try this:
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("c:\boot.ini", ForReading)
Dim arrFileLines()
i = 0
Do Until objFile.AtEndOfStream
Redim Preserve arrFileLines(i)
arrFileLines(i) = objFile.ReadLine
i = i + 1
Loop
objFile.Close
I have a text in some file like
<Variable name="URL" value="http://url:port"/>
I want the url in the value tag( http://url:port ).
The command and regex I'm using are
FindStr /R /C:"\"URL\" *value=*\"*\"" <filename>
The above regex matches the line in the file but fails to extract that url string
any suggestion?
findstr will not capture any values for you. If you can download tools, you can try gawk for windows
C:\test>gawk "/value/{ gsub(/.*value=\042|\042.*/,\"\");print }" file
http://url:port
If not, you can use vbscript
strFile= WScript.Arguments(0)
Set objFS = CreateObject( "Scripting.FileSystemObject" )
Set d = CreateObject("Scripting.Dictionary")
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
strLine=objFile.ReadLine
If InStr(strLine,"value=") > 0 Then
s=Split(strLine,"value=")
s1=Replace(s(1),"/>","")
WScript.Echo s1
End If
Loop
usage:
C:\test>cscript //nologo test.vbs file
"http://url:port"
I'm taking this approach to add a line SOME TEXT TO BE ADDED to the top of an existing file. Is there a way to specify the exact line number to add the new text. For example, before the last line (and add a line break) or after the 3rd line (and add a line break)
copy original.txt temp.txt
echo.SOME TEXT TO BE ADDED>original.txt
type temp.txt >>original.txt
del temp.txt
Vbscript
strLineNum = WScript.Arguments(0)
strAddText= WScript.Arguments(1)
strFileName = WScript.Arguments(2)
Set objFS = CreateObject( "Scripting.FileSystemObject" )
Set objFile = objFS.OpenTextFile(strFileName)
Do Until objFile.AtEndOfStream
linenum=objFile.Line
strLine = objFile.ReadLine
If linenum = CInt(strLineNum) Then
WScript.Echo strAddText
End If
WScript.Echo strLine
Loop
objFile.Close
Usage:
C:\test> cscript //nologo myscript.vbs 2 "text to insert" file >temp
C:\test> ren temp file