Move-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
function Move-EWSItem {
    [CmdletBinding(
            ConfirmImpact = 'Medium',
            SupportsShouldProcess
    )]
    param (
        [Parameter(
                Mandatory
        )]
        [ValidateScript({
                    $root, $rest = $_ -split '\\|/|:|\|'
                    try { 
                        [Microsoft.Exchange.WebServices.Data.WellKnownFolderName]$root 
                        $true
                    } catch {
                        throw "Root folder must belong to WellKnownFolderName: $_"
                    }
        })]
        [string]$DestinationPath,

        [Parameter(
                ValueFromPipeline,
                Mandatory
        )]
        [Microsoft.Exchange.WebServices.Data.Item]$Item,
        
        [Parameter(
                ValueFromPipelineByPropertyName
        )]
        [Microsoft.Exchange.WebServices.Data.ExchangeService]$Service = $Script:exchangeService

    )

    begin {

        $Mailbox = $Connections[$Service]
        $name = [Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName
        $rootName, $remaingPath = $DestinationPath -split '\\|/|:|\|'
        try {
            $rootId = New-Object Microsoft.Exchange.WebServices.Data.FolderId $rootName, $Mailbox
        } catch {
            throw "Unexpected error occurred: $_"
        }
        $root = [Microsoft.Exchange.WebServices.Data.Folder]::Bind(
            $Service,
            $rootId
        )

        foreach ($pathItem in $remaingPath) {
            $filter = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo -ArgumentList @(
                $name,
                $pathItem
            )
            try {
                $new = $root.FindFolders($filter,1).Folders[0]
                if ($new) {
                    $root = $new
                }
            } catch {
                Write-Error "Could not find sub-folder: $pathItem"
                $root
                return
            }
        }
        $destination = $root
    }

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

        if ($PSCmdlet.ShouldProcess(
                $Item.Subject,
                "Move to $DestinationPath"
        )) { 
            $Item.Move($destination.Id)
        }
    }
    end {
        if (-not $Service) {
            Write-Warning 'No connection defined. Use Connect-EWSService first!'
            return
        }
    }
}