Functions/CatalogItems/Write-RsCatalogItem.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
# Copyright (c) 2016 Microsoft Corporation. All Rights Reserved.
# Licensed under the MIT License (MIT)


function Write-RsCatalogItem
{
    <#
        .SYNOPSIS
            Uploads an item from disk to a report server.

        .DESCRIPTION
            Uploads an item from disk to a report server.
            Currently, we are only supporting Report, DataSource, DataSet and jpg/png for uploads

        .PARAMETER Path
            Path to item to upload on disk.

        .PARAMETER RsFolder
            Folder on reportserver to upload the item to.

        .PARAMETER Name
            Specify the Name to be used for the report.

        .PARAMETER Description
            Specify the description to be added to the report.

        .PARAMETER Overwrite
            Overwrite the old entry, if an existing catalog item with same name exists at the specified destination.

        .PARAMETER Hidden
            Mark the item as hidden on the destination server.

        .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.

        .EXAMPLE
            Write-RsCatalogItem -ReportServerUri 'http://localhost/reportserver_sql2012' -Path c:\reports\monthlyreport.rdl -RsFolder /monthlyreports

            Description
            -----------
            Uploads the report monthlyreport.rdl to folder /monthlyreports
    #>

    [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'Medium')]
    param(
        [Parameter(Mandatory = $True, ValueFromPipeline = $true)]
        [string[]]
        $Path,

        [Alias('DestinationFolder')]
        [Parameter(Mandatory = $True)]
        [string]
        $RsFolder,

        [string]
        $Name,

        [string]
        $Description,

        [Alias('Override')]
        [switch]
        $Overwrite,

        [switch]
        $Hidden,

        [string]
        $ReportServerUri,

        [Alias('ReportServerCredentials')]
        [System.Management.Automation.PSCredential]
        $Credential,

        $Proxy
    )

    Begin
    {
        $Proxy = New-RsWebServiceProxyHelper -BoundParameters $PSBoundParameters
        $namespace = $proxy.GetType().Namespace
        $propertyDataType = "$namespace.Property"
    }

    Process
    {
        foreach ($item in $Path)
        {
            #region Manage Paths
            if (!(Test-Path $item))
            {
                throw "No item found at the specified path: $item!"
            }

            $EntirePath = Convert-Path $item
            $item = Get-Item $EntirePath
            $itemType = Get-ItemType $item.Extension
            if ([string]::IsNullOrEmpty($Name))
            {
                $itemName = $item.BaseName
            }
            else
            {
                $itemName = $Name
            }

            if (
                (
                    $itemType -ne "Report" -and
                    $itemType -ne "DataSource" -and
                    $itemType -ne "DataSet" -and
                    $itemType -ne "Resource"
                ) -or
                (
                    $itemType -eq "Resource" -and
                    $item.Extension -notin ('.png', '.jpg', '.jpeg')
                )
            )
            {
                throw "Invalid item specified! You can only upload Report, DataSource, DataSet and jpg/png files using this command!"
            }

            if ($RsFolder -eq "/")
            {
                Write-Verbose "Uploading $EntirePath to /$($itemName)"
            }
            else
            {
                Write-Verbose "Uploading $EntirePath to $RsFolder/$($itemName)"
            }
            #endregion Manage Paths

            if ($PSCmdlet.ShouldProcess("$itemName", "Upload from $EntirePath to Report Server at $RsFolder"))
            {
                #region Upload DataSource
                if ($itemType -eq 'DataSource')
                {
                    try
                    {
                        [xml]$content = Get-Content -Path $EntirePath -ErrorAction Stop
                    }
                    catch
                    {
                        throw (New-Object System.Exception("Failed to access XML content of '$EntirePath': $($_.Exception.Message)", $_.Exception))
                    }

                    if ($item.Extension -eq '.rsds')
                    {
                        if ($content.DataSourceDefinition -eq $null)
                        {
                            throw "Data Source Definition not found in the specified file: $EntirePath!"
                        }
    
                        $NewRsDataSourceParam = @{
                            Proxy = $Proxy
                            RsFolder = $RsFolder
                            Name = $itemName
                            Extension = $content.DataSourceDefinition.Extension
                            ConnectionString = $content.DataSourceDefinition.ConnectString
                            Disabled = ("false" -like $content.DataSourceDefinition.Enabled)
                            CredentialRetrieval = 'None'
                            Overwrite = $Overwrite
                        }
                    }
                    elseif ($item.Extension -eq '.rds')
                    {
                        if ($content -eq $null -or 
                            $content.RptDataSource -eq $null -or
                            $content.RptDataSource.Name -eq $null -or
                            $content.RptDataSource.ConnectionProperties -eq $null -or
                            $content.RptDataSource.ConnectionProperties.ConnectString -eq $null -or
                            $content.RptDataSource.ConnectionProperties.Extension -eq $null)
                        {
                            throw 'Invalid data source file!'
                        }

                        $connectionProperties = $content.RptDataSource.ConnectionProperties
                        $credentialRetrieval = "None"
                        if ($connectionProperties.Prompt -ne $null)
                        {
                            $credentialRetrieval = "Prompt"
                            $prompt = $connectionProperties.Prompt
                        }
                        elseif ($connectionProperties.IntegratedSecurity -eq $true)
                        {
                            $credentialRetrieval = "Integrated"
                        }
                        $NewRsDataSourceParam = @{
                            Proxy = $Proxy
                            RsFolder = $RsFolder
                            Name = $content.RptDataSource.Name
                            Extension = $connectionProperties.Extension
                            ConnectionString = $connectionProperties.ConnectString
                            Disabled = $false
                            CredentialRetrieval = $credentialRetrieval
                            Overwrite = $Overwrite
                        }

                        if ($credentialRetrieval -eq "prompt")
                        {
                            $NewRsDataSourceParam.Add("Prompt", $prompt)
                            $NewRsDataSourceParam.Add("WindowsCredentials", $true)
                        }
                    }
                    else
                    {
                        throw 'Invalid data source file specified!'
                    }

                    New-RsDataSource @NewRsDataSourceParam
                }
                #endregion Upload DataSource

                #region Upload other stuff
                else
                {
                    $additionalProperties = New-Object System.Collections.Generic.List[$propertyDataType]
                    $property = New-Object $propertyDataType

                    if ($itemType -eq 'Resource')
                    {
                        #If it is a resource we need to save the extension so the file can be recognized
                        $itemName = $item.Name
                        $property.Name = 'MimeType'
                        if ($item.Extension -eq ".png")
                        {
                            $property.Value = 'image/png'
                        }
                        else
                        {
                            $property.Value = 'image/jpeg'
                        }
                        $errorMessageItemType = 'resource'
                    }
                    else
                    {
                        $property.Name = 'Description'
                        $property.Value = $Description
                        $errorMessageItemType = 'catalog'
                    }

                    $additionalProperties.Add($property)

                    if ($Hidden)
                    {
                        $hiddenProperty = New-Object $propertyDataType
                        $hiddenProperty.Name = 'Hidden'
                        $hiddenProperty.Value = $Hidden
                        $additionalProperties.Add($hiddenProperty)
                    }
                
                    $bytes = [System.IO.File]::ReadAllBytes($EntirePath)
                    $warnings = $null
                    try
                    {
                        $Proxy.CreateCatalogItem($itemType, $itemName, $RsFolder, $Overwrite, $bytes, $additionalProperties, [ref]$warnings) | Out-Null
                        if ($warnings)
                        {
                            foreach ($warn in $warnings)
                            {
                                Write-Warning $warn.Message
                            }
                        }
                    }
                    catch
                    {
                        throw (New-Object System.Exception("Failed to create $errorMessageItemType item $($item.FullName) : $($_.Exception.Message)", $_.Exception))
                    }
                }
                #endregion Upload other stuff

                Write-Verbose "$EntirePath was uploaded to $RsFolder successfully!"
            }
        }
    }
}