Get-EWSItem.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
function Get-EWSItem {
    [OutputType('Microsoft.Exchange.WebServices.Data.Item')]
    [CmdletBinding(
            DefaultParameterSetName = 'byId'
    )]
    param (

        [Parameter(
                Position = 0
        )]
        [string]$Filter,

        [Parameter(
                ParameterSetName = 'byId',
                ValueFromPipelineByPropertyName,
                Mandatory
        )]
        [Microsoft.Exchange.WebServices.Data.FolderId]$Id,

        [Parameter(
                ParameterSetName = 'byName',
                Mandatory
        )]
        [Microsoft.Exchange.WebServices.Data.WellKnownFolderName]$Name,
    
        [Parameter(
                ValueFromPipelineByPropertyName
        )]
        [Microsoft.Exchange.WebServices.Data.ExchangeService]$Service = $Script:exchangeService,

        [Microsoft.Exchange.WebServices.Data.BasePropertySet]$PropertySet,

        [ValidateRange(1,1000)]
        [Int]$PageSize = 100,

        [Int]$Limit
    )

    process {
        if (-not $Service) {
            return
        }

        $secondParameter = switch ($PSCmdlet.ParameterSetName) {
            byId {
                $Id
            }
            byName {
                $Name
            }
        }
        
        $folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind(
            $Service,
            $secondParameter
        )

        if ($Limit -and $Limit -lt $PageSize) {
            $PageSize = $Limit
        }

        $view = New-Object Microsoft.Exchange.WebServices.Data.ItemView $PageSize, 0
        do {
            if ($Filter) {
                $list = $Folder.FindItems($Filter, $view)
            } else {
                $list = $Folder.FindItems($view)
            }

            if ($PropertySet -and $list.TotalCount) {
                $set = New-Object Microsoft.Exchange.WebServices.Data.PropertySet $PropertySet
                $Service.LoadPropertiesForItems(
                    $list,
                    $set
                ) | Out-Null
            }
            $list
            $view.Offset += $list.Items.Count
            if ($view.Offset -ge $Limit) {
                break
            }
        } while ($list.MoreAvailable)
    }

    end {
        if (-not $Service) {
            Write-Warning 'No connection defined. Use Connect-EWSService first!'
        }
    }
}