Search text in files with ColdFusion and findstr

The code below is a simple example of how to use the windows built-in findstr tool. Findstr tool can be used to search for specific text patterns in files. It’s very similar to the grep command on Linux OS. The example below shows how to use findstr to search the IIS log files.

<Cfset settings = {}>
<Cfset settings.iislogfolder = "C:\logs\LogFiles\W3SVC1\">
<Cfset settings.findstrpath = "C:\Windows\System32\findstr.exe">

<Cfif isdefined("form.action")>
	<Cfif form.action eq 'search' and
	structKeyExists(form,"LOGFILES") and
	form.q neq ''>

		<Cfset report = {}>
		<Cfset report.data = "">
		<Cfset report.files = "">
		<Cfset helper = {}>

		<cfloop list="#form.LOGFILES#" delimiters=", " item="li">
			<Cfset report.files = "#report.files# #settings.iislogfolder##li#">
		</cfloop> 

		<cfexecute name = "#settings.findstrpath#" 
			arguments="/N ""#form.q#"" #report.files#"
			variable="searchResults"
			timeout = "120">
		</cfexecute>
		<Cfset report.data = searchResults>
	</Cfif>
</Cfif>

<cfoutput>
<!DOCTYPE HTML>
<HTML>
<head>
<style>
* {line-height:24px;}
form>div {display:flex;width:400px;margin-bottom:5px;}
form>div.checkbox>label {flex:1;cursor:pointer;}
form>div.checkbox>input[type=checkbox] {width:30px; none;text-align:left;margin-top:6px;padding:0px;}
form>div.text>input[type=text] {flex:1;padding:0px 4px;}
form>div.submit>input[type=submit] {height:32px;flex:1;}

textarea {width:100%;height:300px;overflow-x:scroll;white-space: nowrap; }
</style>
</head>
<body>

<cfif isdefined("report")><textarea>#report.data#</textarea></cfif>

<div><b>Search log files</b></div>
<form autocomplete="off" id="searchLogs" method="post" action="?">
	<input type="hidden" name="action" value="search">
	<cfdirectory action="list" directory="#settings.iislogfolder#" recurse="false" type="file" name="qryDir">
	<cfloop query="qryDir">
	<div class="checkbox">
		<input checked id="checkbox#qryDir.currentrow#" name="logfiles" value="#qryDir.name#" type="checkbox" >
		<label for="checkbox#qryDir.currentrow#">#Name#</label>
	</div>
	</cfloop>
	<div class="text">
		<input placeholder="Search for" name="q" id="q" type="text" />
	</div>
	<div class="submit">
		<input type="submit" value="Search in log files"/>
	</div>

</form>
</body>
</html>
</cfoutput>

More about the buitl-in findstr tool: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/findstr

Leave a Reply

Your email address will not be published. Required fields are marked *