So I'm writing a powershell script to help sort data I have, but I need that data in a certain format.
FN: ORG: Title Tel: Email:
Example A Exam A Exa A EX A EA
Example B Exam B Exa B Ex B EB
However, the output I'm getting is:
FN:Example A
ORG:Exam A
Title:Exa A
Tel: EX A
Email: ExA
FN: Example B
ORG:Exam B
Title: Exa A
Email: EX B
What I wrote is:
> ls *.vcf|%{cat $_ >>"result.txt"} Get-Content "result.txt" |
> Select-String -Pattern
> '(FN:)|(ORG:)|(TITLE:)|(TEL;WORK;VOICE:)|(EMAIL;)'>>new.csv
As I'm sure everyone can tell, I'm very new to this and trying to teach myself. Any help is greatly appreciated.
CodePudding user response:
You're probably looking for something like the following:
Get-ChildItem *.vcf |
ForEach-Object {
$oht = [ordered] @{} # Ordered helper hashtable
# Find all lines of interest in the file at hand, split them into
# field name and value, and add to the hashtable.
$_ |
Select-String -Pattern '^(FN|ORG|TITLE|TEL;WORK;VOICE|EMAIL):(.*)' |
ForEach-Object { $oht[$_.Matches[0].Groups[1]] = $_.Matches[0].Groups[2] }
# Convert the hashtable to a custom object that Export-Csv understands
# and output it.
[pscustomobject] $oht
} |
Export-Csv -Encoding utf8 new.csv # Adapt the encoding as needed.