Functions/CatalogItems/New-RsSubscription.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# Copyright (c) 2016 Microsoft Corporation. All Rights Reserved.
# Licensed under the MIT License (MIT)

function New-RsSubscription
{
    <#
        .SYNOPSIS
            This script creates a new reporting subscription.

        .DESCRIPTION
            This script creates a new reporting subscription based on the parameters provided. NOTE: A new subscriptionId will be generated.

        .PARAMETER RsItem
            Specify the path to the destination report.

        .PARAMETER ReportServerUri
            Specify the Report Server URL to your SQL Server Reporting Services Instance. Use the "Connect-RsReportServer" function to set/update a default value.

        .PARAMETER Credential
            Specify the credentials to use when connecting to the Report Server. Use the "Connect-RsReportServer" function to set/update a default value.

        .PARAMETER Proxy
            Report server proxy to use. Use "New-RsWebServiceProxy" to generate a proxy object for reuse. Useful when repeatedly having to connect to multiple different Report Server.

        .PARAMETER Description
            The description of the schedule.

        .PARAMETER EventType
            The event which triggers the schedule. Specify either 'TimedSubscription' or 'SnapshotUpdated'.
            Default: 'TimedSubscription'.

        .PARAMETER DeliveryMethod
            The delivery method. Specify either 'FileShare' or 'Email'.

        .PARAMETER Schedule
            Either a shared schedule ID or an XML block representing the desired schedule. You can use "New-RsScheduleXML" function to generate the required XML.
            Required if -EventType 'TimedSubscription' has been used.

        .PARAMETER RenderFormat
            Specify the output format of the report. Must be one of 'PDF','MHTML','IMAGE','CSV','XML','EXCELOPENXML','ATOM','PPTX','WORDOPENXML'

        .PARAMETER To
            Use with -DeliveryMethod 'Email' to specify email addresses.

        .PARAMETER CC
            Use with -DeliveryMethod 'Email' to specify CC email addresses.

        .PARAMETER BCC
            Use with -DeliveryMethod 'Email' to specify BCC email addresses.

        .PARAMETER ReplyTo
            Use with -DeliveryMethod 'Email' to specify ReplyTo email address.

        .PARAMETER Subject
            Use with -DeliveryMethod 'Email' to specify the subject line of the email.

        .PARAMETER ExcludeReport
            Use with -DeliveryMethod 'Email' to exclude the report from the email.

        .PARAMETER ExcludeLink
            Use with -DeliveryMethod 'Email' to exclude a link back to the report from the email.

        .PARAMETER Priority
            Use with -DeliveryMethod 'Email' to set the priority with which the e-mail message is sent. Valid values are LOW, NORMAL, and HIGH. The default value is NORMAL.

        .PARAMETER Comment
            Use with -DeliveryMethod 'Email' to specify a comment in the email.

        .PARAMETER FileSharePath
            Use with -DeliveryMethod 'FileShare' to specify the destination location of the generated report. Must be a UNC path.

        .PARAMETER FileShareCredentials
            Use with -DeliveryMethod 'FileShare' to specify the credentials to use when writing file to fileshare. If no credentials are specified, then Execution Account or Service Account credentials are used.

        .PARAMETER FileName
            Use with -DeliveryMethod 'FileShare' to specify the filename of the generated report.

        .PARAMETER FileWriteMode
            Use with -DeliveryMethod 'FileShare' to specify the write behaviour when a file of the same name already exists. Valid values are NONE, OVERWRITE and AUTOINCREMENT.

        .EXAMPLE
            New-RsSubscription -RsItem '/path/to/my/Report' -Description 'Daily to folder' -RenderFormat 'PDF' -Schedule (New-RsScheduleXML -Daily 1) -DeliveryMethod 'FileShare' -FileSharePath '\\Myserver\folder' -FileName 'MyReport' -FileWriteMode Overwrite

            Description
            -----------
            This command will establish a connection to the Report Server located at http://localhost/ReportServer using current user's credentials and create a subscription for report '/path/to/my/Report' that outputs and overwrites the report in PDF format to the specified file share path and name on a daily basis at the current time.

        .EXAMPLE
            New-RsSubscription -RsItem '/path/to/my/Report' -Description 'Daily to folder' -RenderFormat 'PDF' -Schedule (New-RsScheduleXML -Daily 1) -DeliveryMethod 'FileShare' -FileSharePath '\\Myserver\folder' -FileName 'MyReport' -FileWriteMode None

            Description
            -----------
            This command will establish a connection to the Report Server located at http://localhost/ReportServer using current user's credentials and create a subscription for report '/path/to/my/Report' that outputs the report in PDF format to the specified file share path and name (as long as another file with same name does NOT exists) on a daily basis at the current time.

        .EXAMPLE
            New-RsSubscription -RsItem '/path/to/my/Report' -Description 'Daily to folder' -RenderFormat 'PDF' -Schedule (New-RsScheduleXML -Daily 1) -DeliveryMethod 'FileShare' -FileSharePath '\\Myserver\folder' -FileName 'MyReport' -FileWriteMode AutoIncrement

            Description
            -----------
            This command will establish a connection to the Report Server located at http://localhost/ReportServer using current user's credentials and create a subscription for report '/path/to/my/Report' that outputs the report in PDF format to the specified file share path and name (to a new file) on a daily basis at the current time.

        .EXAMPLE
            New-RsSubscription -RsItem '/path/to/my/Report' -Description 'Daily to folder' -RenderFormat 'PDF' -Schedule (New-RsScheduleXML -Daily 1) -DeliveryMethod 'FileShare' -FileSharePath '\\Myserver\folder' -FileName 'MyReport' -FileWriteMode Overwrite -FileShareCredentials (Get-Credential)

            Description
            -----------
            This command will establish a connection to the Report Server located at http://localhost/ReportServer using current user's credentials and create a subscription for report '/path/to/my/Report' that outputs and overwrites the report in PDF format to the specified file share path and name using the specified $FileShareCredentials on a daily basis at the current time.

        .EXAMPLE
            New-RsSubscription -RsItem '/path/to/my/Report' -Description 'Fortnightly by email' -RenderFormat 'WordOpenXML' -Schedule (New-RsScheduleXML -Weekly -Interval 2 -DaysOfWeek Saturday) -DeliveryMethod 'Email' -Subject 'Fortnightly report' -To 'test@someaddress.com'

            Description
            -----------
            This command will establish a connection to the Report Server located at http://localhost/ReportServer using current user's credentials and create a subscription for report '/path/to/my/Report' that outputs the report in Word format by email to the specified recipient every other Saturday at the current time.
        
        .EXAMPLE
            New-RsSubscription -RsItem '/path/to/my/Report' -Description "One minute from now" -RenderFormat 'MHTML' -Schedule (New-RsScheduleXML -Once -StartDate [datetime]::Now.AddMinutes(1)) -DeliveryMethod 'Email' -Subject 'One minute from now' -To 'Christopher.Wren@example.com' -Priority 'HIGH' -ExcludeLink -Comment 'Check this report out!'

            Description
            -----------
            This command will establish a connection to the Report Server located at http://localhost/ReportServer using current user's credentials and create a subscription for report '/path/to/my/Report' that outputs the report in MHTML format by email to the specified recipient one minute from now, with HIGH priority, without a link back to the report and a comment saying 'Check this report out'

        .EXAMPLE
            New-RsSubscription -ReportServerUri 'http://myserver/ReportServer' ...

            Description
            -----------
            This command will establish a connection to the Report Server located at http://myserver/ReportServer using current user's credentials and create a subscription based on other parameters specified.

        .EXAMPLE
            $rsProxy = New-RsWebServiceProxy -ReportServerUri 'http://myserver/ReportServer'
            New-RsSubscription -Proxy $rsProxy ...

            Description
            -----------
            This command will establish a connection to the Report Server located at http://myserver/ReportServer using current user's credentials and create a subscription based on other parameters specified.
    #>

    
    [cmdletbinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium', DefaultParameterSetName='FileShare')]
    param(
        [string]
        $ReportServerUri,

        [System.Management.Automation.PSCredential]
        $Credential,

        $Proxy,

        [Alias('ReportPath','ItemPath','Path')]
        [Parameter(Mandatory=$True)]
        [string]
        $RsItem,

        [string]
        $Description,

        [ValidateSet('TimedSubscription','SnapshotUpdated')] 
        [string]
        $EventType = 'TimedSubscription',

        [Parameter(Mandatory=$True)]
        [string]
        $Schedule,

        [Parameter(Mandatory=$True)]
        [ValidateSet('Email','FileShare')] 
        [string]
        $DeliveryMethod,

        [Parameter(Mandatory=$True)]
        [ValidateSet('PDF','MHTML','IMAGE','CSV','XML','EXCELOPENXML','ATOM','PPTX','WORDOPENXML')]
        [string]
        $RenderFormat = 'PDF',

        [Parameter(ParameterSetName='Email',Mandatory=$True)]
        [string]
        $To,

        [Parameter(ParameterSetName='Email')]
        [string]
        $CC,

        [Parameter(ParameterSetName='Email')]
        [string]
        $BCC,

        [Parameter(ParameterSetName='Email')]
        [string]
        $ReplyTo,

        [Parameter(ParameterSetName='Email')]
        [switch]
        $ExcludeReport,

        [Parameter(ParameterSetName='Email',Mandatory=$True)]
        [string]
        $Subject,

        [Parameter(ParameterSetName='Email')]
        [string]
        $Comment,

        [Parameter(ParameterSetName='Email')]
        [switch]
        $ExcludeLink,

        [Parameter(ParameterSetName='Email')]
        [ValidateSet('LOW', 'NORMAL', 'HIGH')]
        [string]
        $Priority = 'NORMAL',

        [Alias('DestinationPath')]
        [Parameter(ParameterSetName='FileShare',Mandatory=$True)]
        [string]
        $FileSharePath,

        [Parameter(ParameterSetName='FileShare')]
        [System.Management.Automation.PSCredential]
        $FileShareCredentials,

        [Parameter(ParameterSetName='FileShare',Mandatory=$True)]
        [string]
        $Filename,

        [Parameter(ParameterSetName='FileShare')]
        [ValidateSet('None','Overwrite','AutoIncrement')]
        [string]
        $FileWriteMode = 'Overwrite'
    )

    Begin
    {
        $Proxy = New-RsWebServiceProxyHelper -BoundParameters $PSBoundParameters
    }
    Process
    {
        if ([System.String]::IsNullOrEmpty($RsItem))
        {
            throw 'No report path was specified! You need to specify -RsItem variable.'
        }

        try
        {
            Write-Verbose "Validating if target report exists..."
            if (((Get-RsFolderContent -Proxy $Proxy -RsFolder ((Split-Path $RsItem -Parent).Replace('\','/')) | Where-Object Path -eq $RsItem).Count) -eq 0)
            {
                Write-Warning "Can't find the report $RsItem. Skipping."
                Continue
            }

            $Namespace = $Proxy.GetType().NameSpace

            switch ($DeliveryMethod)
            {
                'Email'
                {
                    $Params = @{
                        TO = $To
                        CC = $CC
                        BCC = $BCC
                        ReplyTo = $ReplyTo
                        IncludeReport = (-not $ExcludeReport)
                        IncludeLink = (-not $ExcludeLink)
                        Subject = $Subject
                        Comment = $Comment
                        RenderFormat = $RenderFormat
                        Priority = $Priority
                    }
                }
                'FileShare'
                {
                    $Params = @{
                        PATH = $FileSharePath
                        FILENAME = $Filename
                        RENDER_FORMAT = $RenderFormat
                        WRITEMODE = $FileWriteMode
                    }

                    if ($FileShareCredentials -ne $null)
                    {
                        $Params.USERNAME = $FileShareCredentials.UserName
                        $Params.PASSWORD = $FileShareCredentials.GetNetworkCredential().Password
                        $Params.DEFAULTCREDENTIALS = $false
                    }
                    else
                    {
                        $Params.DEFAULTCREDENTIALS = $true
                    }
                }
            }

            $ParameterValues = @()
            $Params.GetEnumerator() | ForEach-Object {
                $ParameterValues = $ParameterValues + (New-Object "$Namespace.ParameterValue" -Property @{ Name = $_.Name; Value = $_.Value })
            }

            $ExtensionSettings = New-Object "$Namespace.ExtensionSettings" -Property @{ Extension = "Report Server $DeliveryMethod"; ParameterValues = $ParameterValues }

            $MatchData = $Schedule
            $ReportParameters = $Null

            if ($PSCmdlet.ShouldProcess($RsItem, "Creating new subscription"))
            {
                Write-Verbose "Creating Subscription..."
                $subscriptionId = $Proxy.CreateSubscription($RsItem, $ExtensionSettings, $Description, $EventType, $MatchData, $ReportParameters)

                [pscustomobject]@{
                    NewSubscriptionId = $subscriptionId
                }

                Write-Verbose "Subscription created successfully! Generated subscriptionId: $subscriptionId"
            }
        }
        catch
        {
            throw (New-Object System.Exception("Exception occurred while creating subscription! $($_.Exception.Message)", $_.Exception))
        }
    }
}