Reputation: 37
I have a set of .txt
files in a folder. For example:
1.txt
2.txt
3.txt
These contain a date following by a filename. For example, 1.txt
may contain:
06/11/2017 randomdocument.txt
06/12/2017 otherdocument.txt
07/11/2017 yadocument.txt
01/02/2017 randomdocument.txt
I want to:
My code does the first part. I've tried various iterations with no cigar with the second part. Any help would be appreciated.
Code
Set-Location c:\users\john.smith\desktop\FORREPORT
$files = Get-ChildItem -recurse
$SearchPattern = "0[5,6]{1}/[0-9]\w{1,2}/2017"
Foreach ($file in $files) {
$line = Get-ChildItem -recurse | Get-Content | Select-String $SearchPattern
$d = $line | Select-Object file.FullName
$d | Add-Content -path c:\users\john.smith\desktop\ohsnap.txt
}
Desired Output:
06/12/2017 randomdocument.txt in c:\users\john.smith\desktop\FORREPORT\1.txt
Upvotes: 0
Views: 2875
Reputation: 10019
With minimal changes to the code:
Set-Location c:\users\john.smith\desktop\FORREPORT
$files = Get-ChildItem -recurse
$SearchPattern = "0[5,6]{1}/[0-9]\w{1,2}/2017"
Foreach ($file in $files) {
$lines = Get-Content $file | Select-String $SearchPattern
if($lines){
foreach($line in $lines){
"$line`t$($file.FullName)" | Add-Content -path c:\users\john.smith\desktop\ohsnap.txt
}
}
}
This prints each line on a new line in the new document. If you want all matching lines on a single line, remove the foreach
:
Set-Location c:\users\john.smith\desktop\FORREPORT
$files = Get-ChildItem -recurse
$SearchPattern = "0[5,6]{1}/[0-9]\w{1,2}/2017"
Foreach ($file in $files) {
$lines = Get-Content $file | Select-String $SearchPattern
if($lines){
"$lines`t$($file.FullName)" | Add-Content -path c:\users\john.smith\desktop\ohsnap.txt
}
}
if will also check see that matched lines were actually found so that you don't get ouput of just $file.Fullname
with $lines
is empty.
PS Your question and code are the best examples I can think of to use this quote. heed it! ;-p
Upvotes: 0