Powershell - 如何在foreach循环中显示下一个$行

时间:2012-06-06 18:07:03

标签: powershell foreach line

我正在解析.cpp文件中的字符串,需要一种使用_T语法显示多行字符串块的方法。要排除一行_T字符串,我包含了一个-notmatch“;”用于排除它们的参数。这也排除了我需要的字符串块的最后一行。所以我需要显示下一个字符串,以便最后一个字符串块带“;”包括在内。

我试过$ foreach.moveNext()| out-file C:/T_Strings.txt -append但没有运气。

非常感谢任何帮助。 :)

    foreach ($line in $allLines)

    {

    $lineNumber++

    if ($line -match "^([0-9\s\._\)\(]+$_=<>%#);" -or $line -like "*#*" -or $line -like "*\\*" -or $line -like "*//*" -or $line -like "*.dll* *.exe*")
    {
        continue
    } 

    if ($line -notlike "*;*" -and $line -match "_T\(\""" ) # Multiple line strings
    {
        $line | out-file C:/T_Strings.txt -append
        $foreach.moveNext() | out-file C:/T_Strings.txt -append
    }

2 个答案:

答案 0 :(得分:1)

在您的示例中,$foreach不是变量,因此您无法在其上调用方法。如果你想要一个迭代器,你需要创建一个:

$iter = $allLines.GetEnumerator()

do
{
    $iter.MoveNext()
    $line = $iter.Current
    if( -not $line )
    {
        break
    }
} while( $line )

我建议你不要使用正则表达式。改为解析C ++文件。这是我能想到解析所有 _T字符串的最简单的事情。它无法处理:

  • 注释掉_T strings
  • a _)in _T string
  • 文件末尾的_T字符串。

您必须自己添加这些支票。如果你只想要多行_T字符串,你也必须过滤出单行字符串。

$inString = $false
$strings = @()
$currentString = $null

$file = $allLines -join "`n"
$chars = $file.ToCharArray()
for( $idx = 0; $idx < $chars.Length; ++$idx )
{
    $currChar = $chars[$idx]
    $nextChar = $chars[$idx + 1]
    $thirdChar = $chars[$idx + 2]
    $fourthChar = $chars[$idx + 3]

    # See if the current character is the start of a new _T token
    if( -not $inString -and $currChar -eq '_' -and $nextChar -eq 'T' -and $thirdChar -eq '(' -and $fourthChar -eq '"' )
    {
        $idx += 3
        $inString = $true
        continue
    }

    if( $inString )
    {
        if( $currChar -eq '"' -and $nextChar -eq ')' )
        {
            $inString = $false
            if( $currentString )
            {
                $strings += $currentString
            }
            $currentString = $null
        }
        else
        {
            $currentString += $currChar
        }
    }
}

答案 1 :(得分:1)

找出执行此操作的语法:

$foreach.movenext()
$foreach.current | out-file C:/T_Strings.txt -append

您需要移动到下一个,然后管道当前的foreach值。