Get-ChildItem -recurse | Select-String -Pattern "abcd"

Below command line works fine, I want to get the string "abcd" information for all types of files in the drive , at present this command gives output only for .txt file.


thanks in the advance


Get-ChildItem -recurse | Select-String -Pattern "abcd" | group path | select name
LVL 3
SAM ITAD windows Admin Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ben Personick (Previously QCubed)Lead Network EngineerCommented:
A select string wouldn't be the correct option here, instead, you should use a filter on the get-childitem

$Path="C:\Your\Path"
$Pattern="*ABCD*"
Get-ChildItem -Path $Path -Recurse -Filter $Pattern

Open in new window


Also, you grouped them by the path so you'll have to select the group and parse it's objects to get the names:

$Path="C:\Your\Path"
$Pattern="*ABCD*"
$(Get-ChildItem -Path $Path -Recurse -Filter $Pattern | group path ).Group | Select name

Open in new window


Since you only grouped by paths you didn't change the sort order as PowerShell is still looking through the paths sequentially, therefore you could omit the grouping entirely for the same result:

$Path="C:\Your\Path"
$Pattern="*ABCD*"
Get-ChildItem -Path $Path -Recurse -Filter $Pattern | Select name

Open in new window

2
SAM ITAD windows Admin  Author Commented:
getting blank output.

given script unable to fetch keyword from files like docx , xlsx .

I think we need add new-object -comobject word.application to filter keyword from word document
0
Ben Personick (Previously QCubed)Lead Network EngineerCommented:
Hey SamIT,

  The way I read your question, you wanted to match files which have a CD in their file name.

  If you want to read files and find the text PowerShell will only do so for text files using the select-string method this way.

Instead you need to create a list of word documents, and then iterate over them in a loop to see if they contain the string you're looking for after importing the word document handler

$path = "c:\your\path"
WordApp = New-Object -comobject word.application

$WordApp.visible = $false

$WordDocs = Get-childitem -path $Path -Recurse -Include *.doc,*.docx

$matchCase = $false

$matchWholeWord = $false

$matchWildCards = $false

$matchSoundsLike = $false

$matchAllWordForms = $false

$forward = $true

$wrap = 1

$findText = "ABCD"

$i = 0

Foreach ($doc in $WordDocs) {
$i++
      Write-Progress -Activity "Processing files" -status "Processing $($doc.FullName)" -PercentComplete ($i /$docs.Count * 100)

      $document = $application.documents.open($doc.FullName)

    $content = $document.content

  
   $content.find.execute($findText,$matchCase,$matchWholeWord,$matchWildCards,$matchSoundsLike,$matchAllWordForms,$forward,$wrap)

     If ($wordFound) {
          $Results+=$($doc.FullName)
     }
     $wordfound=0
}

$Results
 




 #clean up stuff

[System.Runtime.InteropServices.Marshal]::ReleaseComObject($range) | Out-Null

[System.Runtime.InteropServices.Marshal]::ReleaseComObject($document) | Out-Null

[System.Runtime.InteropServices.Marshal]::ReleaseComObject($application) | Out-Null

Remove-Variable -Name WordApp

[gc]::collect()

[gc]::WaitForPendingFinalizers()

Open in new window


I haven't really dealt with this much because it's a total pain, and so I had to look up a good reference, and the code above is based off the information I found in the MSPowershell scripting guy's post.

You can see that post here.

  I did this comment entirely on mobile and have not checked it is working, so please check thatg link for more details if it does not work exactly as desired.
1
Simplify Active Directory Administration

Administration of Active Directory does not have to be hard.  Too often what should be a simple task is made more difficult than it needs to be.The solution?  Hyena from SystemTools Software.  With ease-of-use as well as powerful importing and bulk updating capabilities.

footechCommented:
If what you want is to search the contents of all files, then PowerShell is (probably) not what you want.  Perhaps it could be done with a great deal of effort, but the built-in cmdlets will only handle plain-text files.

For searching within other types of files you need a product that includes parsers for all the different file types.  The closest you can get with built-in functionality is via the Windows Indexing (Search) service, as Windows includes iFilters for a number of different file types, and you may be able to install iFilters for other types as well (like .PDF - not sure if Win10 includes this in-box, but Win7 didn't).  Of course for this to work, the location you want to search has to be included in the indexing options.

The script at https://gallery.technet.microsoft.com/scriptcenter/Get-IndexedItem-PowerShell-5bca2dae is great for searching the index (run the script to create the function).
Syntax for running the function would be like:
Get-IndexedItem -path C:\Users\someuser\Documents -recurse -Filter "abcd"

Open in new window

However, I don't think it does a good job with partial matches.

There are other products out there to help with needs like this, like https://www.x1.com/products/x1_search/
0
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
If you really mean "all types of files" - you can't, without adding code for each individual file type different from plain text.

Asking Windows Search can help, given that the locations to search are included in the index. Windows Search knows a lot about installed applications, their associated file types and how to extract information from them.
An example query is
$sql = "select System.ItemName, System.ItemUrl, System.ItemPathDisplay from SYSTEMINDEX WHERE scope = 'file:C:/Doc/' and contains(*, 'arp')"
$adapter = new-object system.data.oledb.oleDBDataadapter -argument $sql, "Provider=Search.CollatorDSO;Extended Properties=’Application=Windows’;"
$ds      = new-object system.data.dataset
if ($adapter.Fill($ds)) { $ds.Tables[0] }

Open in new window

to query C:\Doc and subfolders ('scope' - if you use 'path', no recursion) for all (known) fields containing 'arp'.
You can even use a scope like 'mapi://' to go through your emails associated with Outlook.
If you need more details about how to create an appropriate select statement, see e.g. https://blogs.technet.microsoft.com/heyscriptingguy/2010/05/30/hey-scripting-guy-weekend-scripter-using-the-windows-search-index-to-find-specific-files/
1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
footechCommented:
After doing more investigation around the issue of partial matches and Windows Search, I found that use of wildcards is only valid at the end of a string.  So something like "comp*" would be valid, but "*comp*" would not.  With a wildcard, the search must match the beginning of the word.  Example: for the word "computer", you could match "comp*", but you can't match "put" or "*put" or "*put*".

I was able to improve the capability of the script I linked to above, but I can't be sure it didn't impact some other functionality of the script without more extensive testing (I just know it worked for a .doc file).

The change to Qlemo's code to allow a wildcard would be:
$sql = "select System.ItemName, System.ItemUrl, System.ItemPathDisplay from SYSTEMINDEX WHERE scope = 'file:C:/Doc/' and contains(*, '`"arp*`"')"

Open in new window

1
SAM ITAD windows Admin  Author Commented:
Hello Ben,

Getting below error post script execution.

______________________________________________

The term 'WordApp' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:2 char:8
+ WordApp <<<<  = New-Object -comobject word.application
    + CategoryInfo          : ObjectNotFound: (WordApp:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
 
Property 'visible' cannot be found on this object; make sure it exists and is settable.
At line:4 char:10
+ $WordApp. <<<< visible = $false
    + CategoryInfo          : InvalidOperation: (visible:String) [], RuntimeException
    + FullyQualifiedErrorId : PropertyNotFound
 
Attempted to divide by zero.
At line:28 char:111
+       Write-Progress -Activity "Processing files" -status "Processing $($doc.FullName)" -PercentComplete ($i / <<<< $docs.Count * 100)
    + CategoryInfo          : NotSpecified: (:) [], RuntimeException
    + FullyQualifiedErrorId : RuntimeException
 
You cannot call a method on a null-valued expression.
At line:30 char:46
+       $document = $application.documents.open <<<< ($doc.FullName)
    + CategoryInfo          : InvalidOperation: (open:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
0
SAM ITAD windows Admin  Author Commented:
Hello Qlemo,

Given script by you works perfectly as expected.  Is there possible way to add multiple keywords to search ? like below one
______________________
and contains(*, 'arp')"
0
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
In Ben's code line 2 a $ is missing at the very start - it should be $WordApp.

In the search SQL for Windows Search you can combine keywords with logic operators, you just need to make sure to do correctly ;-). For example (just showing the WHERE clause):
WHERE scope = 'file:C:/Doc/' and (contains(*, 'arp') or contains(*,'network'))

Open in new window

4
SAM ITAD windows Admin  Author Commented:
Hello  Qlemo

Getting below error post script execution with combine keywords
___________
Exception calling "Fill" with "1" argument(s): "One or more errors occurred during processing of command.
IErrorInfo.GetDescription failed with E_FAIL(0x80004005)."
At line:4 char:18
+ if ($adapter.Fill <<<< ($ds)) { $ds.Tables[0] }
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException
0
SAM ITAD windows Admin  Author Commented:
issue resolved.. thanks Q
0
SAM ITAD windows Admin  Author Commented:
thanks qlemo
0
SAM ITAD windows Admin  Author Commented:
perfect solution
0
footechCommented:
I am really wondering why only Qlemo's post(s) were selected as the answer, given that mine mention the same thing, and the script I linked to does the same searches of the Windows Search Index.
2
Ben Personick (Previously QCubed)Lead Network EngineerCommented:
@footech, SamIT generally doesn't divide the points for help provided in my experiance, so ymmv.

  It's always fairly subjective as in this case, and its his oppinion and his peeagative that only Qlemo's answer was worthy of points.

  Its the sort of thi ng that is a little frustrating, but at the same time, its never been blatently wrong, like assigning points only to a non-solution, although not how I might divvy points, but that doesn't make it wrong per-se.
2
footechCommented:
@Ben - I completely understand that someone may choose a different solution than one I provided.  My only issue here was that my and Qlemo's post contain close to the same information, posted at the same time, which is a great example of when points should be split.
1
SAM ITAD windows Admin  Author Commented:
@footech - apologies

I missed out you to split the points, any possible way still I can split the points now?
0
Ben Personick (Previously QCubed)Lead Network EngineerCommented:
Hello there, glad to help, even if it was only to determine that you wanted file contents ^^ have a good one. :)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.