O R G A N I C / F E R T I L I Z E R: using powershell to replace “find” or “findstr”

Dec 2, 2008

using powershell to replace “find” or “findstr”

this is one of those things i’m blogging to remind myself instead of bugging hal rottenberg. :)

in order to find something inside a list of files, you can use find or findstr. what’s the difference between those? findstr is a bit more robust, accepting pattern matches with regex, for example. in most cases though, i’m just looking for a string inside of a list of text files. so here we go with find and the general output we can expect…

C:\temp>find /i "wscript.echo" *.*

---------- DATE2INTEGER8.VBS
' wscript.Echo CurrentDate(Now)
' WScript.Echo CurrentDate(dDateThreshold)
      WScript.Echo oRecordSet.Fields("cn") & ":" & oRecordSet.Fields("displayname") & ":" & Integer8Date(oRecordSet.Fields("pwdlastset").Value,lBias)

---------- DLNAMES.TXT

---------- DNS_DEBUG.LOG

---------- TEMP_SCRIPT.SM
 WScript.Echo
 WScript.Echo "=========================================="
 WScript.Echo "Computer: " & strComputer
 WScript.Echo "=========================================="
    WScript.Echo "ArpAlwaysSourceRoute: " & objItem.ArpAlwaysSourceRoute
    WScript.Echo "ArpUseEtherSNAP: " & objItem.ArpUseEtherSNAP

i was kind of perturbed about having to switch back and forth from cmd shell to powershell so i asked hal about it one day… and he told me to use select-string. it turns out if acts differently if you don’t pipe anything to select-string. as you can see, the output is much nicer too …

[12] » Select-String -SimpleMatch -Pattern "wscript.echo" -Path *.* | Format-Table filename, linenumber, line -autosize

Filename          LineNumber Line
--------          ---------- ----
date2integer8.vbs         11 ' wscript.Echo CurrentDate(Now)
date2integer8.vbs         12 ' WScript.Echo CurrentDate(dDateThreshold)
date2integer8.vbs         33     WScript.Echo oRecordSet.Fields("cn") & ":" &
temp_script.sm             8    WScript.Echo
temp_script.sm            10    WScript.Echo "Computer: " & strComputer
temp_script.sm            18       WScript.Echo "ArpAlwaysSourceRoute: " &
temp_script.sm            19       WScript.Echo "ArpUseEtherSNAP: " &
temp_script.sm            20       WScript.Echo "Caption: " & objItem.Caption

i purposely wrote the command verbosely for clarity. to be succinct, in this case, you’ll get the same result with:

ss "wscript.echo" *.* | ft f*, l* -auto