Как добавить многострочные строки в массив в powershell? - PullRequest
1 голос
/ 16 июня 2019

Я пытаюсь перебрать серию txt-файлов, извлекающих информацию в массивы на основе: delimiter.

Все значения, которые я беру из текстовых файлов, помещаются в одну строку, кроме одной. (Значение "текст объявления"). Это обрезает информацию после строки 1 в конечном выводе. Когда я заранее удаляю переносы строк и разрывы, ни одно из полей не вводится правильно.

Как бы я указал, чтобы мой массив принимал многострочные входные данные для поля "текст объявления"?

Ниже приведен код, с которым я работаю:

$files = ls "*.txt" 
$dictionary = @{} 
[System.Collections.Generic.List[String]]$list = @() 

foreach($f in $files){$in = Get-Content $f
 $in.Split([Environment]::NewLine) | ForEach-Object { $key,$value = $_.Split(':') 
 $dictionary[$key] = $value 
 }

[void]$list.Add( $dictionary['Ad ID'] + ',' + $dictionary['Ad Text'] + ',' + $dictionary['Ad Landing Page'] + ',' + $dictionary['Ad Targeting Location'] + ',' + $dictionary['Age'] + ',' + $dictionary['Language'] + ',' + $dictionary['Placements'] + ',' + $dictionary['Interests'] + ',' + $dictionary['Behaviors'] + ',' + $dictionary['Ad Impressions'] + ',' + $dictionary['Ad Clicks'] + ',' + $dictionary['Ad Spend'] + ',' + $dictionary['Ad Creation Date'] + ','+ $dictionary['Friends'] + ',' + $dictionary['Ad End Date'] + ',' + $dictionary['Excluded Connections'] + ',' + $dictionary['Image'] + ',' + $dictionary['Ad Targeting Location']+','+$dictionary[‘File Name’] ) 
} 


$list | Out-File -FilePath '.\trial.csv' -Append

1 Ответ

3 голосов
/ 16 июня 2019

Предполагая, что дополнительные строки после Ad Text: строк с префиксом не содержат : самих символов:

# Create sample text file t.txt
@'
Ad ID:10
Ad Text:one
two
Ad Landing Page:http://example.org
'@ > t.txt

# Split the lines into field names and values by ":" and
# build a dictionary.
$dict = [ordered] @{}
$i = 0
(Get-Content -Raw t.txt) -split '(?m)^([^\n:]+):' -ne '' | ForEach-Object {
  if ($i++ % 2 -eq 0) {
    $key = $_
  } else {
    $dict[$key] = $_
  }
}

# Output the dictionary, showing each entry as a list.
$dict | Format-List

Вывод выглядит следующим образом, показывая, что запись Ad Text состоит из двух строк:

Name  : Ad ID
Value : 10


Name  : Ad Landing Page
Value : http://example.org


Name  : Ad Text
Value : one
        two
...