子串越来越少的数据

时间:2016-07-21 08:37:38

标签: powershell

我想在--Start--End评论之间从.sql文件中获取大量文本内容。

无论我做什么,我都没有正确地获取子串方法来只获取--Start和--End注释中的文本:

text.sql

This text I want not
--Start
this text I want here
--End
This text I want not

这就是我的尝试:

$insertStartComment = "--Start"
$insertEndComment = "--End"

$content = [IO.File]::ReadAllText("C:\temp\test.sql")
$insertStartPosition =  $content.IndexOf($insertStartComment) + $insertStartComment.Length

$insertEndPosition =    $content.IndexOf($insertEndComment)
$content1 = $content.Substring($insertStartPosition, $content1.Length - $insertEndPosition)
$content = $content1.Substring(0,$content1.Length - $insertEndPosition)

如果有人可以帮我找到我的错误会很好: - )

2 个答案:

答案 0 :(得分:0)

尝试在代码中使用未初始化的变量:

$content1 = $content.Substring($insertStartPosition, $content1.Length - $insertEndPosition)

变量$content1尚未初始化,因此子字符串调用变得混乱。当你再次运行代码时,变量被设置 - 结果更加奇怪。

使用Powershell的Set-StrictMode启用有关未初始化变量的警告。

答案 1 :(得分:0)

这不是您正在寻找的子串方法,但我认为我会抛出一个RegEx解决方案。这将在文本文件中找到--Start和--End之间的文本。在这种情况下,我将匹配的文本与名为LineYouWant的命名捕获分组,并显示它找到的匹配项。如果在单个文件中有多个--Start - End块实例,这也可以使用。

Sub findData()
Dim workflow As String
Dim finalrow As Integer
Dim i As Integer
Dim StartTime as Date
Dim ExecutionTime as Long

With Sheets("Sheet1")
    workflow = .Range("C5").Value
    servergri = .Range("C9").Value
    gridf = .Range("C9").Value
    On Error Goto Next
    StartTime = .Range("c11").Value
    If Err Then
        MsgBox "You didn't enter a valid start time.", vbExclamation
        Exit Sub
    End If
    ExecutionTime = .Range("c16").Value
    If Err Then
        MsgBox "You didn't enter a valid execution time.", vbExclamation
        Exit Sub
    End If
    On Error Goto 0
End With

With Sheets("Sheet3")
    finalrow = .Range("C" & Rows.Count).End(xlUp).Row

    For i = 5 To finalrow
        If .Cells(i, 3) = workflow And (.Cells(i, 4) = servergri Or .Cells(i, 5) = gridf) Then
            .Rows(i).Insert
            'Add new information to the new row.
            'The new row number is still = i

            .Cells(i, 3) = workflow
            .Cells(i, 4) = servergri
            .Cells(i, 6) = StartTime
                .Cells(i, 3).Resize(2, 4).Interior.ColorIndex = 8

            'You don't mention where this time should go on Sheet 3, so I used Cell(i, 9)
            'TimeSerial(Hours, Minutes, Seconds)
            .Cells(I, 9).Value = StartTime + TimeSerial(0, ExecutionTime, 0) 
            .Cells(I, 9).NumberFormat = "hh:mm"

            'If you only want to add one row then your should exit the loop
            Exit For
        End If
    Next
End With
End Sub