Reputation: 3
I am trying to search a text file for a certain text then output that text to a different text file only if it matches. I'm having troubles creating this. I attached the code I have, but the issue is no matter what it is creating a results.txt file and the file is blank. I only want the results.txt file to be created if the multiplatform_201604110718.txt has CCTK STATUS CODE : SUCCESS inside it.
$Path = "C:\multiplatform_201604110718.txt"
$Text = "CCTK STATUS CODE : SUCCESS"
$PathArray = @()
$Results = "C:\results.txt"
# This code snippet gets all the files in $Path that end in “.txt”.
Get-ChildItem $Path -Filter “*.txt” |
Where-Object { $_.Attributes -ne “Directory”} |
ForEach-Object {
If (Get-Content $_.FullName | Select-String -Pattern $Text) {
$PathArray += $_.FullName
$PathArray += $_.FullName
}
}
Write-Host “Contents of ArrayPath:”
$PathArray | ForEach-Object {$_}
$PathArray | % {$_} | Out-File "C:\Resuts.txt"
Upvotes: 0
Views: 234
Reputation: 5861
If you really only need to check one file you can do it with much less code:
$Text = "CCTK STATUS CODE : SUCCESS"
$p = "C:\Users\kzbx\Desktop\test.txt"
if($ln = Select-String -pattern $text -path $p){
$ln.Line | Out-File C:\result.txt
}
This writes the line in which the text occurs to your result file (if i understood you correctly that is what you need, if not please clarify ;))
Upvotes: 1