Outlook : Powershell : Import contacts from sent items
`$outlook` `= ``new-object` `-com` `outlook.application`
`$olFolders` `= ``"Microsoft.Office.Interop.Outlook.OlDefaultFolders"` `-as` `[type]`
`$namespace` `= ``$outlook``.GetNameSpace(``"MAPI"``)`
`$sentItems` `= ``$namespace``.getDefaultFolder(``$olFolders``::olFolderSentMail)`
`$alreadyAddedEmails` `= @() ``#Empty Array`
`$counter` `= 0;`
`$totalItems` `= ``$sentItems``.items.count;`
`Write-Host` `"Scanning through"` `$totalItems` `"emails in SentItems"`
`$contacts` `= ``$outlook``.Session.GetDefaultFolder(``$olFolders``::olFolderSuggestedContacts)`
`##############################################################################################################`
`# FUNCTION - Adds Name/Email to SuggestedContacts - Unless it has already been added before (by this script).`
`##############################################################################################################`
`Function` `AddToSuggestedContactsIfNotAlreadyAdded (``$name``, ``$email``)`
`{ `
` ``if``((``$name` `-eq` `"``") -or ($email -eq "") -or ($name -eq $null) -or ($email -eq $null)){`
` ``return;`
` ``} `
` ``if ($name -like '*@*') {`
` ``$name = $null`
` ``}`
` ``else {`
` ``$name = $name.Replace("``'``", "").Replace("""", "")`
` ``}`
` ``$contactAlreadyAdded = $false`
` ``foreach ($elem in $global:alreadyAddedEmails) {`
` ``if(($elem.ToLower() -eq $email.ToLower())){`
` ``$contactAlreadyAdded = $true`
` ``if ($name -eq $null) { $name = "``** No Display Name **``" }`
` ``Write-Host ($global:counter)"``/``"($totalItems) "``SKIPPED ``" $name.PadRight(25,"` `") "``-``" $email`
` ``return;`
` ``}`
` ``}`
` ``if(!$contactAlreadyAdded ) {`
` ``$newcontact = $contacts.Items.Add()`
` ``$newcontact.FullName = $name`
` ``$newcontact.Email1Address = $email`
` ``$newcontact.Save()`
` ``$global:alreadyAddedEmails += $email`
` ``if ($name -eq $null) { $name = "``** No Display Name **``" }`
` ``Write-Host ($global:counter)"``/``"($totalItems) "``ADDED ``" $name.PadRight(25,"` `") "``-" ``$email`
` ``}`
`}`
`# Loop through all emails in SentItems`
`$sentItems``.Items | % { `
` ``#Loop through each recipient`
` ``$_``.Recipients | %{`
` ``AddToSuggestedContactsIfNotAlreadyAdded ``$_``.Name ``$_``.Address`
` ``}`
` ``$global:counter` `= ``$global:counter` `+ 1`
`}`