0

我需要搜索多个文件,并且在特定行下,我需要在每个文件中插入先前引用的行。到目前为止,我根本无法让我的脚本正常工作。这是我到目前为止所拥有的:

$TextLocation = "M:\test"
$files = get-childitem -filter *.gto -path $TextLocation

Foreach ($file in $files) {
  $pagetitle = "DS_PGSEQ-DC:"
  $a = Get-Content $file.FullName | Select-String "AssignedToUserID-TZ"
  $b = Get-Content $file.FullName | Select-String "EFormID-TZ"
  Foreach ($line in $file)
  {
    if([String]$line -eq "DS_PGSEQ-DC:0001")
    {
    }
    elseif([String]$line -eq $pagetitle) 
    {
      Add-Content $file.FullName ($a -and $b)
    }
  }
}
4

2 回答 2

0

There are two common ways for inserting text into a text file:

  1. Process the input file(s) line-by-line, write the output to a temporary file and replace the input file(s) with them temp file afterwards.

    for ($file in $files) {
      $filename = $file.FullName
      Get-Content $filename | % {
        if ( $_ -match 'seach pattern' ) {
          $_
          "new line"
        }
      } | Out-File $tempfile
      MoveItem $tempfile $filename -Force
    }
    
  2. Read the entire content of the file(s), insert the text by using a regular expression replacement, and write the modified content back to the file(s).

    for ($file in $files) {
      $text = [System.IO.File]::ReadAllText($file.FullName)
      $text -replace '.*search pattern.*', "`$0`nnew line" |
        Out-File $file.FullName
    }
    
于 2013-06-10T18:10:22.533 回答
0
$TextLocation = "M:\test"
$Outputlocation = "M:\test\output"
$files = get-childitem -filter *.gto -path $TextLocation

Foreach ($file in $files) {
  $pattern = "\d\d\d[2-9]"
  $found=$false
  $contains=$false

  $lines = Get-Content($file.FullName) |
    Foreach-object { 
      if ($_ -match "AssignedToUserID-TZ") {
        $a = $_
      }

      if ($_ -match "EFormID-TZ") {
        $b = $_ 
      }        

      if ($_ -match "DS_PGSEQ-DC:$pattern") {
        if($found -eq $false) {
          $found=$true
        }
      } else {
        $found=$false
      }

      if ($found -eq $true) {
        $contains=$true

        #Add Lines after the selected pattern
        $_
        $a
        $b
      }

      if ($found -ne $true) {
        $_
      }

    } | Set-Content($Outputlocation + "\" + $file.Name)
}
于 2013-06-11T19:06:34.703 回答