我试图将字符串搜索返回的行号转换为变量。
过程
我得到了要返回的行号,但是不知道如何从这里开始使用它。
# Pull files from source directory with extension filter
Get-ChildItem $SourceDirectory -Filter $OutputFileExtension -Recurse |
ForEach-Object {
Select-String $_ -Pattern $TargetString |
Select-Object -ExpandProperty 'LineNumber'
}
答案 0 :(得分:3)
在这方面做了一些工作。这适用于我需要的功能。改进?
# 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
}