简体   繁体   中英

How to automate removing Exchange Contacts in Office365

I am writing a powershell script that:

  1. Compares two CSV files
  2. Output files for: Changes, added, removed contacts
  3. Update and add contacts
  4. Remove contacts

The problem is when I try and removed contacts. Which is done by:

  #Check for Removed Contacts
   foreach($row in $File1_Data )
  {
    $data_found=0
     foreach($id in $emails_id)
      {
       if ($row.ExternalEmailAddress -eq $id)
         {
          $data_found=1

         }

      } 

   if($data_found -eq 0 ) #Email Not Found
      { $row|Select-Object -Property ExternalEmailAddress|Export-Csv -Path $Removed_Contact -Append -NoTypeInformation}

  }

Now I have a file with only the email addresses. The error comes when I try and run the command connected on the exchange server.

$RemoveContacts = Import-CSV ".\Removed Contacts_$((Get-Date).ToString('MMddyyyy')).csv"
$RemoveContacts | ForEach { Remove-MailContact -identity $_ -confirm:$false}

But I get the following error:

Cannot process argument transformation on parameter 'Identity'. Cannot convert the "@{ExternalEmailAddress=testuser@testcompany.com}" value of type "Deserialized.System.Management.Automation.PSCustomObject" to type "Microsoft.Exchange.Configuration.Tasks.MailContactIdParameter". + CategoryInfo : InvalidData: (:) [Remove-MailContact], ParameterBindin...mationException + FullyQualifiedErrorId : ParameterArgumentTransformationError,Remove-MailContact + PSComputerName : outlook.office365.com

$File_Data structure is in the format Microsoft requires . and $emails_id is the function that compares the two csv files. But that's not where the script breaks, that's just how i create the file. What am I missing?

The error message is telling you that it can't convert the value of $_ to what it needs for -Identity parameter. Generally the -Identity parameter for most PS commandlets is going to be the human readable unique name of something. In this case, it would be an email address. With that said the error message is telling you that instead of $_ containing the string version of an email address, it contains a hash or dictionary object that contains a single property, ExternalEmailAddress.

So to make this work, change your $_ to $_.ExternalEmailAddress and now the call to Remove-MailContact will use the value of the ExternalEmailAddress property of the object in your ForEach loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM