I think you are overcomplicating this. Do all of the files have the same “headers” in them with the data separated by colons like the example file I used above? You are trying to use a regex solution which I think is overboard to just pull data out of colon-separated data. If your files had no similarity and say Transaction Type was just hidden in all of this random junk:
Foo DataFoo DataFoo DataFoo DataFoo DataFoo
Foo DataFoo DataFoo Data Transaction Type: 3523tergdgFoo DataFoo DataFoo DataFoo Data
Foo DataFoo DataFoo DataFoo DataFoo DataFoo DataFoo DataFoo Data
Foo DataFoo DataFoo DataFoo DataFoo DataFoo DataFoo DataFoo Data
Foo DataFoo DataFoo DataFoo DataFoo DataFoo DataFoo Data
Foo DataFoo DataFoo DataFoo DataFoo DataFoo Data
In the above, I would use a regex pattern, which is what you are doing in Select-String. However, if your files have the same headers with a colon to separate data, then I would really consider something like this:
#Get all text files
$results = Get-ChildItem C:\Users\rsimmers\Desktop\* -Include *.txt -File | foreach {
#Get the content of the file
$content = Get-Content $_.FullName
#Create a blank hash table for properties
$props = @{}
#Add a property with the File Name
$props.Add("File Name", $_.Name)
foreach($line in $content) {
#Split the line at the colon to make an array
$arrLine = $line.Split(":")
#Add the header ($arrLine[0]) and data ($arrLine[1]) into a hash table
$props.Add(($arrLine[0]).Trim(), ($arrLine[1]).Trim())
}
#Create a new object with the properties and store in $results
New-Object -TypeName PSObject -Property $props
}
$results | Format-Table -AutoSize
I placed 3 text files with the same headers with different data on my desktop and run the script would produce something like this:
File Name Another Column Transaction Type Some Column
--------- -------------- ---------------- -----------
test.txt More Data 3523tergdg Some Data
test1.txt Foo Data 35w46235ythdg Different Data
test2.txt Data Foo o68rg352ty34tyr Junk Data
Now that the files are parsed, you know what file the data came from, you can do whatever you want with it. If you are convinced you have to use regex, to get multiple matches you would do something like this:
$objFSO = New-Object -ComObject Scripting.FileSystemObject
$textFile = $objFSO.OpenTextFile("C:\Users\rsimmers\Desktop\test.txt", 1, $false)
$content = $textFile.ReadAll()
$transaction = ([regex]"Transaction Type:\s+(.*)").match($content).groups[1].value
$anothercolumn = ([regex]"Another Column:\s+(.*)").match($content).groups[1].value
$textFile.Close()
$transaction
$anothercolumn
There are a lot of ways to do things. If you really want help, you need to be specific with what you are trying to do and the challenges you are having. Provide examples and expected results. Tell us how you want to use the data.