Используйте PowerShell и EWS для олицетворения исходного организатора собрания при создании встречи - PullRequest
0 голосов
/ 17 января 2019

Я пытаюсь создать встречу в почтовом ящике ресурса в Exchange Online с помощью API EWS (Exchange Web Services).

Я аутентифицируюсь в EWS, используя глобальную учетную запись администратора O365.

Затем я выдаю себя за организатора, а затем связываюсь с папкой календаря почтового ящика. Для этого я настроил соответствующие роли / области управления.

При создании встречи организатор отображается как учетная запись почтового ящика комнаты, а не как олицетворенная учетная запись. Я не вижу, что я делаю неправильно ...

Я использовал различные источники, чтобы получить меня, насколько я:

https://docs.microsoft.com/en-us/previous-versions/office/developer/exchange-server-2010/dd633680(v=exchg.80)

https://docs.microsoft.com/en-us/exchange/client-developer/exchange-web-services/delegate-access-and-ews-in-exchange

Приведенный ниже код успешно создает встречу в календаре $ roomMailbox, хотя организатор настроен как почтовый ящик комнаты, а не организатор, которого я пытаюсь выдать за себя ...

Любое руководство высоко ценится.

using namespace Microsoft.Exchange.WebServices.Data

Set-StrictMode -Version 5.1

$ErrorActionPreference = 'Stop'

function Connect-EWS
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$false)]
        [System.Management.Automation.PSCredential]$Credential
    )

    try
    {
        [void][Reflection.Assembly]::LoadFile("C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll")
    }
    catch
    {
        throw "Could not import Microsoft Exchange web services library: $($_.Exception.Message)"
    }

    try
    {
        $ews = [ExchangeService]::New()
    }
    catch
    {
        throw "Could not create Microsoft.Exchange.WebServices.Data.ExchangeService object: $($_.Exception.Message)"
    }

    if($credential)
    {
        $ews.Credentials = $Credential.GetNetworkCredential()
    }
    else
    {
        $ews.UseDefaultCredentials = $true
    }

    $validateRedirectionUrlCallback = {

        Param([String]$Url)

        if($Url -eq "https://autodiscover-s.outlook.com/autodiscover/autodiscover.xml")
        {
            return $true
        } 
        else 
        {
            return $false
        }
    }

    try
    {
        $ews.AutodiscoverUrl($Credential.UserName,$validateRedirectionUrlCallback)
    }
    catch
    {
        throw "Autodiscover failed: $($_.Exception.Message)"
    }

    return $ews
}

function New-Appointment
{
    Param
    (
        [Parameter(Mandatory = $true)]
        [String]$Organiser
        ,
        [Parameter(Mandatory = $true)]
        [String]$RoomMailbox
        ,
        [Parameter(Mandatory = $true)]
        [DateTime]$Start
        ,
        [Parameter(Mandatory = $true)]
        [DateTime]$End
        ,
        [Parameter(Mandatory = $true)]
        [String]$Subject
        ,
        [Parameter(Mandatory = $true)]
        [String]$Location
    )


    try # Resolve the organiser ID
    {
        [Void]$ews.ResolveName($Organiser,[ResolveNameSearchLocation]::DirectoryOnly, $false)
    }
    catch
    {
        throw "Could not resolve Organiser identity: $Organiser : $($_.Exception.Message)"
    }

    try # Attempt to enable impersonation as the organiser
    {
        $ews.ImpersonatedUserId = [ImpersonatedUserId]::New([ConnectingIdType]::SmtpAddress, $Organiser)
    }
    catch
    {
        throw "Could not impersonate user $Organiser : $($_.Exception.Message)"
    }

    try # Create a new appointment object
    {
        $appointment = [Appointment]::New($ews)
    }
    catch
    {
        throw "Could not create appointment object: $($_.Exception.MEssage)"
    }

    # Add each of the properties below associated values into the appointment object

    $setProperties = 'Start','End','Subject','Location'

    foreach($p in $setProperties)
    {
        $appointment.$p = Get-Variable $p -ValueOnly
    }

    try # Set the folder ID as the calendar of the room mailbox
    {
        $folderId = [FolderId]::New([WellKnownFolderName]::Calendar, $RoomMailbox)
    }
    catch
    {
        throw "Could not generate target calendar folder id: $($_.Exception.Message)"
    }

    try # Try and bind the EWS connection to the folder
    {
        $folder = [Folder]::Bind($ews, $folderId)
    }
    catch
    {
        throw "Could not bind to user $($folderId.FolderName) $($_.Exception.Message)"
    }

    try # Save the appointment
    {
        $appointment.Save($folderId, [SendInvitationsMode]::SendToAllAndSaveCopy)
    }
    catch
    {
        throw "Could not save appointment as organiser: $Organiser : $($_.Exception.Message)"
    }
}

if(!$credential)
{
    $credential = Get-Credential -UserName $globalAdminUPN -Message "Please enter O365 credentials for user $globalAdminUPN"
}

$Organiser   = 'organiser@domain.com'
$RoomMailbox = 'roommailbox@domain.com'
$Start       = '01/02/2019 22:00'
$End         = '01/02/2019 23:00'
$Subject     = 'Test Appointment'
$Location    = 'Test Location'

$ews = Connect-EWS -Credential $credential

try
{
    New-Appointment -Organiser   $Organiser `
                    -RoomMailbox $RoomMailbox `
                    -Start       $Start `
                    -End         $End `
                    -Subject     $Subject `
                    -Location    $Location
}
catch
{
    Write-Host "ERROR: $($_.Exception.Message)" -ForegroundColor Red
} 

Ответы [ 2 ]

0 голосов
/ 22 января 2019

Кажется, то, что я пытаюсь сделать, невозможно, насколько я могу судить, организатор всегда устанавливается как владелец почтового ящика, в котором создается встреча, независимо от олицетворения / делегирования.

Я изменил способ решения проблемы, создав встречу в календаре организаторов и добавив почтовый ящик комнаты в качестве участника. Это достигает моей цели с тем же правом, что и прежде, а именно, выдавая себя за организатора.

Сценарий ниже содержит функции Connect-EWS и New-Appointment с выполнением тех функций, которые находятся под ними.

Требуется, чтобы учетная запись admin@domain.onmicrosoft.com имела права на персонализацию почтового ящика организаторов.

Это будет работать только для Exchange Online, так как автообнаружение не используется, URL для EWS задается вручную.

using namespace Microsoft.Exchange.WebServices.Data

Set-StrictMode -Version 5.1

$ErrorActionPreference = 'Stop'

function Connect-EWS
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true)]
        [System.Management.Automation.PSCredential]$Credential
    )

    try
    {
        [void][Reflection.Assembly]::LoadFile("C:\Program Files\Microsoft\Exchange\Web Services\2.2\Microsoft.Exchange.WebServices.dll")
    }
    catch
    {
        throw "Could not import Microsoft Exchange web services library: $($_.Exception.Message)"
    }

    try
    {
        $ews = [ExchangeService]::New()
    }
    catch
    {
        throw "Could not create Microsoft.Exchange.WebServices.Data.ExchangeService object: $($_.Exception.Message)"
    }

    if($credential)
    {
        $ews.Credentials = $Credential.GetNetworkCredential()
    }
    else
    {
        $ews.UseDefaultCredentials = $true
    }

    try # Set EWS URL
    {
        $ews.Url = 'https://outlook.office365.com/EWS/Exchange.asmx'
    }
    catch
    {
        throw "Could not set EWS URL: $($_.Exception.Message)"
    }

    return $ews
}

function New-Appointment
{
    Param
    (
        [Parameter(Mandatory = $true)]
        [String]$Organiser
        ,
        [Parameter(Mandatory = $true)]
        [DateTime]$Start
        ,
        [Parameter(Mandatory = $true)]
        [DateTime]$End
        ,
        [Parameter(Mandatory = $true)]
        [String]$Subject
        ,
        [Parameter(Mandatory = $false)]
        [String]$Location
        ,
        [Parameter(Mandatory = $false)]
        [Array]$RequiredAttendees
    )


    try # Resolve the organiser ID
    {
        [Void]$ews.ResolveName($Organiser,[ResolveNameSearchLocation]::DirectoryOnly, $false)
    }
    catch
    {
        throw "Could not resolve Organiser identity: $Organiser : $($_.Exception.Message)"
    }

    try # Attempt to enable impersonation as the organiser
    {
        $ews.ImpersonatedUserId = [ImpersonatedUserId]::New([ConnectingIdType]::SmtpAddress, $Organiser)
    }
    catch
    {
        throw "Could not impersonate user $Organiser : $($_.Exception.Message)"
    }

    try # Create a new appointment object
    {
        $appointment = [Appointment]::New($ews)
    }
    catch
    {
        throw "Could not create appointment object: $($_.Exception.MEssage)"
    }

    try # Add each required attendee to appointment
    {
        foreach($ra in $requiredAttendees)
        {
            [Void]$appointment.RequiredAttendees.Add($ra)
        }
    }
    catch
    {
        throw "Failed to add required attendee: $ra : $($_.Excecption.Message)"
    }

    # Add each of the properties below associated values into the appointment object

    $setProperties = 'Start','End','Subject','Location'

    foreach($p in $setProperties)
    {
        $appointment.$p = Get-Variable $p -ValueOnly
    }

    try # Set the folder ID as the calendar of the room mailbox
    {
        $folderId = [FolderId]::New([WellKnownFolderName]::Calendar, $Organiser)
    }
    catch
    {
        throw "Could not generate target calendar folder id: $($_.Exception.Message)"
    }

    try # Try and bind the EWS connection to the folder
    {
        $folder = [Folder]::Bind($ews, $folderId)
    }
    catch
    {
        throw "Could not bind to mailbox $($folderId.Mailbox) $($_.Exception.Message)"
    }

    try # Save the appointment
    {
        $appointment.Save($folderId, [SendInvitationsMode]::SendToAllAndSaveCopy)
    }
    catch
    {
        throw "Could not save appointment as organiser: $Organiser : $($_.Exception.Message)"
    }
}

$admin = 'admin@domain.onmicrosoft.com'

$credential = Get-Credential -UserName $admin -Message "Please enter O365 credentials for user $admin"

$Organiser   = 'organiser@domain.onmicrosoft.com'
$RoomMailbox = 'roommailbox@domain.onmicrosoft.com'
$Start       = '02/01/2019 12:00'
$End         = '02/01/2019 13:00'
$Subject     = 'Test Appointment'
$Location    = 'Test Location'

$requiredAttendees = $RoomMailbox

$ews = Connect-EWS -Credential $credential

try
{
    New-Appointment -Organiser         $Organiser `
                    -Start             $Start `
                    -End               $End `
                    -Subject           $Subject `
                    -Location          $Location `
                    -RequiredAttendees $requiredAttendees
}
catch
{
    Write-Host "ERROR: $($_.Exception.Message)" -ForegroundColor Red
}
0 голосов
/ 17 января 2019

Почему вы не указали органайзер в этой строке?

$setProperties = 'Start','End','Subject','Location'

* Теперь читаем, что органайзер доступен только для чтения и настраивается автоматически, НО я нашел эту статью Организатор встречи: грязная правда , и здесь упоминается, встреча.

Также проверьте эту ссылку

Добавление встреч с использованием олицетворения Exchange

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...