Advertisement
Guest User

Untitled

a guest
Sep 26th, 2017
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. param([string]$CSVFileName,[string]$EmailAddress,[string]$Username,[string]$Password,[string]$Domain,[bool]$Impersonate,[string]$EwsUrl,[string]$EWSManagedApiPath);
  2.  
  3. #
  4. # Import-CalendarCSV.ps1
  5. #
  6. # By David Barrett, Microsoft Ltd. Use at your own risk.
  7. #
  8.  
  9. Function ShowParams()
  10. {
  11.     Write-Host "Import-CalendarCSV -CSVFileName <string> -EmailAddress <string>";
  12.     Write-Host "                   [-Username <string> -Password <string> [-Domain <string>]]";
  13.     Write-Host "                   [-Impersonate <bool>]";
  14.     Write-Host "                   [-EwsUrl <string>]";
  15.     Write-Host "                   [-EWSManagedApiPath <string>]";
  16.     Write-Host "";
  17.     Write-Host "Required:";
  18.     Write-Host " -CSVFileName : Filename of the CSV file to import appointments for this user from.";
  19.     Write-Host " -EmailAddress : Mailbox SMTP email address";
  20.     Write-Host "";
  21.     Write-Host "Optional:";
  22.     Write-Host " -Username : Username for the account being used to connect to EWS (if not specified, current user is assumed)";
  23.     Write-Host " -Password : Password for the specified user (required if username specified)";
  24.     Write-Host " -Domain : If specified, used for authentication (not required even if username specified)";
  25.     Write-Host " -Impersonate : Set to $true to use impersonation.";
  26.     Write-Host " -EwsUrl : Forces a particular EWS URl (otherwise autodiscover is used, which is recommended)";
  27.     Write-Host " -EWSManagedApiDLLFilePath : Full and path to the DLL for EWS Managed API (if not specified, default path for v1.1 is used)";
  28.     Write-Host "";
  29. }
  30.  
  31. $RequiredFields=@{
  32.     "Subject" = "Subject";
  33.     "StartDate" = "Start Date";
  34.     "StartTime" = "Start Time";
  35.     "EndDate" = "End Date";
  36.     "EndTime" = "End Time"
  37. }
  38.  
  39. # Check email address
  40.  if (!$EmailAddress)
  41.  {
  42.     ShowParams;
  43.     throw "Required parameter EmailAddress missing";
  44.  }
  45.  
  46. # CSV File Checks
  47. if (!$CSVFileName)
  48. {
  49.     ShowParams;
  50.     throw "Required parameter CSVFileName missing";
  51. }
  52. if (!(Get-Item -Path $CSVFileName -ErrorAction SilentlyContinue))
  53. {
  54.     throw "Unable to open file: $CSVFileName";
  55. }
  56.  
  57. # Import CSV File
  58. try
  59. {
  60.     $CSVFile = Import-Csv -Path $CSVFileName;
  61. }
  62. catch { }
  63. if (!$CSVFile)
  64. {
  65.     Write-Host "CSV header line not found, using predefined header: Subject;StartDate;StartTime;EndDate;EndTime";
  66.     $CSVFile = Import-Csv -Path $CSVFileName -header Subject,StartDate,StartTime,EndDate,EndTime;
  67. }
  68.  
  69. # Check file has required fields
  70. foreach ($Key in $RequiredFields.Keys)
  71. {
  72.     if (!$CSVFile[0].$Key)
  73.     {
  74.         # Missing required field
  75.         throw "Import file is missing required field: $Key";
  76.     }
  77. }
  78.  
  79. # Check EWS Managed API available
  80.  if (!$EWSManagedApiPath)
  81.  {
  82.      $EWSManagedApiPath = "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"
  83.      $dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"
  84.  }
  85.  if (!(Get-Item -Path $EWSManagedApiPath -ErrorAction SilentlyContinue))
  86.  {
  87.      throw "EWS Managed API could not be found at $($EWSManagedApiPath).";
  88.  }
  89.  
  90. # Load EWS Managed API
  91.  [void][Reflection.Assembly]::LoadFile($EWSManagedApiPath);
  92.  
  93. # Create Service Object.  We only need Exchange 2007 schema for creating calendar items (this will work with Exchange>=12)
  94. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2016
  95. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)
  96.  
  97. # Set credentials if specified, or use logged on user.
  98. $psCred = Get-Credential
  99.  
  100. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())
  101. $AccountWithImpersonationRights = $psCred.UserName
  102.  if ($Username -and $Password)
  103.  {
  104.      if ($Domain)
  105.      {
  106.          $service.Credentials = New-Object  Microsoft.Exchange.WebServices.Data.WebCredentials($Username,$Password,$Domain);
  107.      } else {
  108.          $service.Credentials = New-Object  Microsoft.Exchange.WebServices.Data.WebCredentials($Username,$Password);
  109.      }
  110.      
  111. } else {
  112.      $service.UseDefaultCredentials = $true;
  113.  }
  114. $service.Credentials = $creds
  115.  
  116. # Set EWS URL if specified, or use autodiscover if no URL specified.
  117. if ($EwsUrl)
  118. {
  119.     $service.URL = New-Object Uri($EwsUrl);
  120. }
  121. else
  122. {
  123.     try
  124.     {
  125.         Write-Host "Performing autodiscover for $EmailAddress";
  126.         #$service.AutodiscoverUrl($EmailAddress);
  127.         $service.AutodiscoverUrl($AccountWithImpersonationRights ,{$true})
  128.     }
  129.     catch
  130.     {
  131.         throw;
  132.     }
  133. }
  134.  
  135. # Bind to the calendar folder
  136.  
  137. if ($Impersonate)
  138. {
  139.     $service.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress,$EmailAddress );
  140. }
  141. try {
  142.     $CalendarFolder = [Microsoft.Exchange.WebServices.Data.CalendarFolder]::Bind($service, [Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar);
  143. } catch {
  144.     throw;
  145. }
  146.  
  147. # Parse the CSV file and add the appointments
  148. foreach ($CalendarItem in $CSVFile)
  149. {
  150.     # Create the appointment and set the fields
  151.     $NoError=$true;
  152.     try
  153.     {
  154.         $Appointment = New-Object Microsoft.Exchange.WebServices.Data.Appointment($service);
  155.         $Appointment.Subject=$CalendarItem."Subject";
  156.         $StartDate=[DateTime]($CalendarItem."StartDate" + " " + $CalendarItem."StartTime");
  157.         $Appointment.Start=$StartDate;
  158.         $EndDate=[DateTime]($CalendarItem."EndDate" + " " + $CalendarItem."EndTime");
  159.         $Appointment.End=$EndDate;
  160.     }
  161.     catch
  162.     {
  163.         # If we fail to set any of the required fields, we will not write the appointment
  164.         $NoError=$false;
  165.     }
  166.    
  167.     # Check for any other fields
  168.     foreach ($Field in ($CalendarItem | Get-Member -MemberType Properties))
  169.     {
  170.         if (!($RequiredFields.Keys -contains $Field.Name))
  171.         {
  172.             # This is a custom (optional) field, so try to map it
  173.             try
  174.             {
  175.                 $Appointment.$($Field.Name)=$CalendarItem.$($Field.Name);
  176.             }
  177.             catch
  178.             {
  179.                 # Failed to write this field
  180.                 Write-Host "Failed to set custom field $($Field.Name)" -ForegroundColor yellow;
  181.             }
  182.         }
  183.     }
  184.  
  185.     if ($NoError)
  186.     {
  187.         # Save the appointment
  188.         $Appointment.Save([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar);
  189.         Write-Host "Created $($CalendarItem."Subject")" -ForegroundColor green;
  190.     }
  191.     else
  192.     {
  193.         # Failed to set a required field
  194.         Write-Host "Failed to create appointment: $($CalendarItem."Subject")" -ForegroundColor red;
  195.     }
  196. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement