2

I'm trying to loop through a series of txt files extracting information into arrays based a : delimiter.

All values i'm taking from the text files fit on a single line, except for one. (The "ad text" value). This cuts off the information after line 1 in the final output. When I remove line carriages and breaks beforehand, none of the fields are inputted correctly.

How would I specify wanting my array to accept multi-line inputs for the "ad text" field?

Below is the code i'm working with:

$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
  • 2
    Get-Content - without -Raw - returns an array of lines, so its elements by definition have no embedded newlines. Commented Jun 15, 2019 at 23:16

1 Answer 1

4

Assuming that the additional lines following Ad Text:-prefixed lines do not contain : chars themselves:

# 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

The output is as follows, showing that the Ad Text entry comprises two lines:

Name  : Ad ID
Value : 10


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


Name  : Ad Text
Value : one
        two
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.