Reputation: 71
I'm trying to get the line number returned on a string search into a variable.
Process
I get the line number to return, but don't know how to work with it from here.
# Pull files from source directory with extension filter
Get-ChildItem $SourceDirectory -Filter $OutputFileExtension -Recurse |
ForEach-Object {
Select-String $_ -Pattern $TargetString |
Select-Object -ExpandProperty 'LineNumber'
}
Upvotes: 3
Views: 13780
Reputation: 71
Did a little more work on this. This functions for what I need. Improvements?
# Pull files from source directory with extension filter
Get-ChildItem $SourceDirectory -Filter $OutputFileExtension |
ForEach-Object {
#Assign variable for total lines in file
$measure = Get-Content $_.FullName | Measure-Object
$TotalLinesInFile = $measure.count
#Assign variable to the line number where $TargetString is found
$LineNumber = Select-String $_ -Pattern $TargetString | Select-Object -ExpandProperty 'LineNumber'
Write-Host "Line where string is found: "$LineNumber
#Store the line number where deletion begins
$BeginDelete = $Linenumber - $LinesToDeleteBefore
Write-Host "Line Begin Delete: "$BeginDelete
#Store the line number where deletion ends
$EndDelete = $LineNumber + $LinesToDeleteAfter
Write-Host "Line End Delete: "$EndDelete
#Assign variable for export file
$OutputFile = $ExportDirectory + $_.Name
#Get file content for update
$FileContent = Get-Content $_.FullName
Write-Host "FileContent: " $FileContent
#Remove unwanted lines by excluding them from the new file
$NewFileContent = $FileContent[0..$BeginDelete] + $FileContent[($EndDelete + $LineToDeleteAfter)..$TotalLinesInFile] | Set-Content $OutputFile
}
Upvotes: 4