I have a textbox that takes an input and searches a drive.
Drive for example is C:/users/me
let's say I have multiple files and subdirectories in there and I would like to search if the following strings exist in the file: "ssn" and "DOB"
Once user inputs the two strings. I split the string but space, so I can loop through the array. But here is my current code, but I'm stuck on how to proceed.
gci "C:\Users\me" -Recurse | where { ($_ | Select-String -pattern ('SSN') -SimpleMatch) -or ($_ | Select-String -pattern ('DOB') -SimpleMatch ) } | ft CreationTime, Name -Wrap -GroupBy Directory | Out-String
this above code works if i pasted it manually into powershell but I'm trying to recreate this in a script but having confusion and how to do so.
this code below is not getting all the files needed.
foreach ($x in $StringArrayInputs) {
if($x -eq $lastItem){
$whereClause = ($_ | Select-String -Pattern $x)
}else{
$whereClause = ($_ | Select-String -Pattern $x) + '-or'
}
$files= gci $dv -Recurse | Where { $_ | Select-String -Pattern $x -SimpleMatch} | ft CreationTime, Name -Wrap -GroupBy Directory | Out-String
}
Select-String's-Patternparameter accepts an array of strings (any one of which triggers a match), so piping directly to a singleSelect-Stringcall should do:Note:
Using
-FilewithGet-ChildItemmakes it return only files, not also directories.Using
-ListwithSelect-Stringis an optimization that ensures that at most one match per file is looked for and reported.Passing
Select-String's output toGet-Itemautomatically binds the.Pathproperty of the former's output to the-Pathparameter of the latter.-Pathsubjects the argument to interpretation as a wildcard expression, which, however, is generally not a concern - except if the path contains[characters.Select-Object @{ Name='LiteralPath'; Expression='Path' }beforeGet-Item, which ensures binding to-LiteralPathinstead.