locked
add appointment to public folder map RRS feed

  • General discussion

  • Hi,

    I have write a program to add appointments to a public folder item

    Param

    ([string]$calInputFile="c:\powershell\rapril.rpt")

    # Load EWS Managed API library

    Import-Module

    -Name"C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"

    # Load all calendar Entries

    $calEntries

    =Import-Csv$calInputFile

    $service

    =New-ObjectMicrosoft.Exchange.WebServices.Data.ExchangeService-ArgumentList([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::$ExchangeVersion)


    $service

    .Url=new-objectSystem.Uri("https://******.driestar.nl/ews/exchange.asmx")



    # Service account must have ApplicationImpersonation ManagementRoleAssignment in Exchange


    $service

    .Credentials=new-objectMicrosoft.Exchange.WebServices.Data.WebCredentials("*******")



    $aiItem

    =New-ObjectMicrosoft.Exchange.WebServices.Data.AlternatePublicFolderId


    $aiItem

    .folderid="0000000053A569D42C60AD4FA4F514CA74B9324B010023878900B4FFB84CB73A22A36D64A38100000005442F0000"


    $aiItem

    .Format=([Microsoft.Exchange.WebServices.Data.IdFormat]::HexEntryId)


    $ewsid

    =$service.ConvertId($aiItem, [Microsoft.Exchange.WebServices.Data.IdFormat]::EWSId)


    $test

    =$ewsid.FolderId


    # Load docent Mailboxes



    foreach

    ($entryin$calEntries)

    {

    # Instruct service to use impersonation


    $appt=New-ObjectMicrosoft.Exchange.WebServices.Data.Appointment($service)

    $appt.Subject=$entry.Onderwerp


    $appt.Start=[System.DateTime]($entry.start)

    $appt.End=[System.DateTime]($entry.eind)    #For AllDayEvent, end date must be after start date


    $appt.LegacyFreeBusyStatus="Free"


    $appt.IsReminderSet=$False


    $appt.Save($ewsid,([Microsoft.Exchange.WebServices.Data.SendInvitationsMode]::SendToNone))

    }

     This is the result:

    Cannot find an overload for "Save" and the argument count: "2".

    At C:\powershell\addvakantietest in outlook.ps1:35 char:2

    +     $appt.Save($ewsid,([Microsoft.Exchange.WebServices.Data.SendInvitationsMode]::S ..

    .

    +    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        + CategoryInfo          : NotSpecified: (:) [], MethodException

        + FullyQualifiedErrorId : MethodCountCouldNotFindBest

    What is wrong in this script???


    Thursday, April 10, 2014 1:25 PM

All replies

  • You need to pass in a FolderId object to the save method, your just passing the FolderId String eg take

    $folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId($ewsid)

    and then

    $appt.Save($folderid,([Microsoft.Exchange.WebServices.Data.SendInvitationsMode]::SendToNone))

    You might want try something like this instead of doing the ConvertId to get the FolderId eg

    ## Get the Mailbox to Access from the 1st commandline argument
    
    $MailboxName = $args[0]
    
    ## Load Managed API dll  
    Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"  
      
    ## Set Exchange Version  
    $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2  
      
    ## Create Exchange Service Object  
    $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)  
      
    ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials  
      
    #Credentials Option 1 using UPN for the windows Account  
    $psCred = Get-Credential  
    $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())  
    $service.Credentials = $creds      
      
    #Credentials Option 2  
    #service.UseDefaultCredentials = $true  
      
    ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates  
      
    ## Code From http://poshcode.org/624
    ## Create a compilation environment
    $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
    $Compiler=$Provider.CreateCompiler()
    $Params=New-Object System.CodeDom.Compiler.CompilerParameters
    $Params.GenerateExecutable=$False
    $Params.GenerateInMemory=$True
    $Params.IncludeDebugInformation=$False
    $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null
    
    $TASource=@'
      namespace Local.ToolkitExtensions.Net.CertificatePolicy{
        public class TrustAll : System.Net.ICertificatePolicy {
          public TrustAll() { 
          }
          public bool CheckValidationResult(System.Net.ServicePoint sp,
            System.Security.Cryptography.X509Certificates.X509Certificate cert, 
            System.Net.WebRequest req, int problem) {
            return true;
          }
        }
      }
    '@ 
    $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
    $TAAssembly=$TAResults.CompiledAssembly
    
    ## We now create an instance of the TrustAll and attach it to the ServicePointManager
    $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
    [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll
    
    ## end code from http://poshcode.org/624
      
    ## Set the URL of the CAS (Client Access Server) to use two options are availbe to use Autodiscover to find the CAS URL or Hardcode the CAS to use  
      
    #CAS URL Option 1 Autodiscover  
    $service.AutodiscoverUrl($MailboxName,{$true})  
    "Using CAS Server : " + $Service.url   
       
    #CAS URL Option 2 Hardcoded  
      
    #$uri=[system.URI] "https://casservername/ews/exchange.asmx"  
    #$service.Url = $uri    
      
    ## Optional section for Exchange Impersonation  
      
    #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName) 
    
    function FolderIdFromPath{
    	param (
    	        $FolderPath = "$( throw 'Folder Path is a mandatory Parameter' )"
    		  )
    	process{
    		## Find and Bind to Folder based on Path  
    		#Define the path to search should be seperated with \  
    		#Bind to the MSGFolder Root  
    		$folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::PublicFoldersRoot)   
    		$tfTargetFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
    		#Split the Search path into an array  
    		$fldArray = $FolderPath.Split("\") 
    		 #Loop through the Split Array and do a Search for each level of folder 
    		for ($lint = 1; $lint -lt $fldArray.Length; $lint++) { 
    	        #Perform search based on the displayname of each folder level 
    	        $fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(1) 
    	        $SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,$fldArray[$lint]) 
    	        $findFolderResults = $service.FindFolders($tfTargetFolder.Id,$SfSearchFilter,$fvFolderView) 
    	        if ($findFolderResults.TotalCount -gt 0){ 
    	            foreach($folder in $findFolderResults.Folders){ 
    	                $tfTargetFolder = $folder                
    	            } 
    	        } 
    	        else{ 
    	            "Error Folder Not Found"  
    	            $tfTargetFolder = $null  
    	            break  
    	        }     
    	    }  
    		if($tfTargetFolder -ne $null){
    			return $tfTargetFolder.Id.UniqueId.ToString()
    		}
    	}
    }
    #Example use
    $fldId = FolderIdFromPath -FolderPath "\test\calendar"
    if($fldId -ne "Error Folder Not Found"){
    	$SubFolderId =  new-object Microsoft.Exchange.WebServices.Data.FolderId($fldId)
    	$SubFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$SubFolderId)
    
    	$NewAppointment = New-Object Microsoft.Exchange.WebServices.Data.Appointment -ArgumentList $service  
    	$NewAppointment.Subject = "Test Appointment"
    	$NewAppointment.Start = (Get-Date)
    	$NewAppointment.End = (Get-Date).AddHours(1)
    	$NewAppointment.Save($SubFolder.Id,([Microsoft.Exchange.WebServices.Data.SendInvitationsMode]::SendToNone))  
    	
    }
    
    Cheers
    Glen

    Friday, April 11, 2014 5:57 AM
  • Thanks Glen,

    I am now be able to put appointments in a public folder of exchange 2013

    Friday, April 11, 2014 9:59 AM