Thursday, January 13, 2011

Powershell VCards (text file splitting)

I ran into a problem today that I figured I'd share. The exported addressbook format for GroupWise wouldn't work with Outlook, even though it supported the VCard format, the GroupWise client exported the entire address book in a signle .VCF file, which Outlook didn't support.

While not a good solution, I decided to split up the .VCF file with a script and make multiple .VCF files that could be imported to Outlook.

$ifile = $args[0]

If($ifile -eq $NULL)
Write-Host Usage: .\vcfrw.ps1 filename.vcf
Write-Host Examp: .\vcfrw.ps1 h:\vcf\joe.vcf

Write-Host Prossessing GroupWise VCard File: $ifile

$i = 1
switch -regex -file $ifile
"^BEGIN:VCARD" {if($FString){$FString | out-file -Encoding "ASCII" _
"$ifile.$i.vcf"};$FString = $_;$i++}
"^(?!BEGIN:VCARD)" {$FString += "`r`n$_"}

Write-Host VCard Processing Complete
Write-Host Processed $i VCard entries

The biggest problem I had was with the out-file, my first runs generated .VCF files that looked valid, but Outlook would not read them. After a little searching I learned that out-file by default used Unicode format, and Outlook needed them to be ASCII. hence the -Encoding "ASCII" in the script.

1 comment:

Anonymous said...

I had the reverse problem. Here is something to get started for taking all vcf files and generating a VERY rough csv file.
# Run this script with the following command:
# .\vcfReader.ps1 | out-file "AllContacts.csv" -encoding ascii

# Get all the *.vcf files in the current directory.
$vcfFiles = gci *.vcf

foreach ($file in $vcfFiles) {
# Write-Host Prossessing $file -foregroundcolor green
if (Test-Path "$file") {
$phone = ""
$vcfFile = get-Content "$file"

foreach ($line in $vcfFile) {
if ($line.substring(0,1) -eq "N") {
# "FOUND NAME: $line"
$name = $line

if ($line.substring(0,3) -eq "TEL") {
# "FOUND PHONE: $line"
$phone = $phone + $line
"$name, $phone"