Invoke-RemoteScript.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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
Add-Type -AssemblyName System.Net.Http

$writeStreamOverridesScript = {
    if($PSVersionTable.PSVersion.Major -ge 5) {
        function Write-Information {
            param([string]$Message)
            $InformationPreference = "Continue"
            Microsoft.PowerShell.Utility\Write-Information -Message $Message 6>&1
        }
    }
    function Write-Debug {
        param([string]$Message)
        $DebugPreference = "Continue"
        Microsoft.PowerShell.Utility\Write-Debug -Message $Message 5>&1
    }
    function Write-Verbose {
        param([string]$Message)
        $VerbosePreference = "Continue"
        Microsoft.PowerShell.Utility\Write-Verbose -Message $Message 4>&1
    }
    function Write-Warning {
        param([string]$Message)
        $WarningPreference = "Continue"
        Microsoft.PowerShell.Utility\Write-Warning -Message $Message 3>&1
    }
    function Write-Error {
        param([string]$Message)
        $WarningPreference = "Continue"
        Microsoft.PowerShell.Utility\Write-Error -Message $Message 2>&1
    }
}

function Parse-Response {
    param(
        [string]$Response,
        [bool]$HasRedirectedMessages,
        [bool]$Raw
    )
    if($response) {
        $parsedResponse = $response
        $responseMessages = ""
        if($Raw) {
            if($parsedResponse.Contains("<#messages#>")) {
                $parsedResponse = $parsedResponse -split "<#messages#>"
            }
            if($parsedResponse -is [string[]]) {
                $parsedResponse[0]
                if($parsedResponse.Length -gt 1) {
                    $responseMessages = $parsedResponse[1]
                    $hasRedirectedMessages = $true
                }
            } elseif(![string]::IsNullOrEmpty($parsedResponse)) {
                $parsedResponse
            }
        } elseif($parsedResponse) {
            $responseMessages = $parsedResponse
        }

        if(![string]::IsNullOrEmpty($responseMessages)) {
            if ($hasRedirectedMessages) {
                Write-Verbose -Message "Redirecting output to the appropriate stream."
                foreach ($record in ConvertFrom-CliXml -InputObject $responseMessages) {
                    if ($record -is [PSObject] -and $record.PSObject.TypeNames -contains "Deserialized.System.Management.Automation.VerboseRecord") {
                        Write-Verbose $record.ToString()
                    }
                    elseif ($record -is [PSObject] -and $record.PSObject.TypeNames -contains "Deserialized.System.Management.Automation.InformationRecord") {
                        Write-Information $record.ToString()
                    }
                    elseif ($record -is [PSObject] -and $record.PSObject.TypeNames -contains "Deserialized.System.Management.Automation.DebugRecord") {
                        Write-Debug $record.ToString()
                    }
                    elseif ($record -is [PSObject] -and $record.PSObject.TypeNames -contains "Deserialized.System.Management.Automation.WarningRecord") {
                        Write-Warning $record.ToString()
                    }
                    elseif ($record -is [PSObject] -and $record.PSObject.TypeNames -contains "Deserialized.System.Management.Automation.ErrorRecord") {
                        Write-Error $record.ToString()
                    }
                    else {
                        $record
                    }
                }
            }
            else {
                Write-Verbose -Message "Deserializing the response message from the server."                     
                ConvertFrom-CliXml -InputObject $responseMessages
            }
        }
    } elseif ($response -eq "login failed") {
        Write-Verbose "Login with the specified account failed."
        break            
    } else {
        Write-Verbose "No response returned by the service. If results were expected confirm that the service is enabled and the account has access. A common cause for this is an application pool recycling."
    }
}

function Invoke-RemoteScript {
    <#
        .SYNOPSIS
            Run scripts in Sitecore PowerShell Extensions via web service calls.
 
        .DESCRIPTION
            When using commands such as Write-Verbose, be sure the preference settings are configured properly.
 
            Change each of these to "Continue" in order to see the message appear in the console.
 
            Example values:
 
            ConfirmPreference High
            DebugPreference SilentlyContinue
            ErrorActionPreference Continue
            InformationPreference SilentlyContinue
            ProgressPreference Continue
            VerbosePreference SilentlyContinue
            WarningPreference Continue
            WhatIfPreference False
     
        .EXAMPLE
            The following example remotely executes a script in Sitecore using a reusable session.
     
            $session = New-ScriptSession -Username admin -Password b -ConnectionUri http://remotesitecore
            Invoke-RemoteScript -Session $session -ScriptBlock { Get-User -id admin }
            Stop-ScriptSession -Session $session
     
            Name Domain IsAdministrator IsAuthenticated
            ---- ------ --------------- ---------------
            sitecore\admin sitecore True False
     
        .EXAMPLE
            The following remotely executes a script in Sitecore with the $Using variable.
 
            $date = [datetime]::Now
            $script = {
                $Using:date
            }
     
            Invoke-RemoteScript -ConnectionUri "http://remotesitecore" -Username "admin" -Password "b" -ScriptBlock $script
            Stop-ScriptSession -Session $session
     
            6/25/2015 11:09:17 AM
                     
        .EXAMPLE
            The following example runs a script as a ScriptSession job on the server (using Start-ScriptSession internally).
            The arguments are passed to the server with the help of the $Using convention.
            The results are finally returned and the job is removed.
             
            $session = New-ScriptSession -Username admin -Password b -ConnectionUri http://remotesitecore
            $identity = "admin"
            $date = [datetime]::Now
            $jobId = Invoke-RemoteScript -Session $session -ScriptBlock {
                [Sitecore.Security.Accounts.User]$user = Get-User -Identity $using:identity
                $user.Name
                $using:date
            } -AsJob
            Start-Sleep -Seconds 2
 
            Invoke-RemoteScript -Session $session -ScriptBlock {
                $ss = Get-ScriptSession -Id $using:JobId
                $ss | Receive-ScriptSession
 
                if($ss.LastErrors) {
                    $ss.LastErrors
                }
            }
            Stop-ScriptSession -Session $session
         
        .EXAMPLE
            The following remotely executes a script in Sitecore with arguments.
             
            $script = {
                [Sitecore.Security.Accounts.User]$user = Get-User -Identity admin
                $user
                $params.date.ToString()
            }
     
            $args = @{
                "date" = [datetime]::Now
            }
     
            Invoke-RemoteScript -ConnectionUri "http://remotesitecore" -Username "admin" -Password "b" -ScriptBlock $script -ArgumentList $args
            Stop-ScriptSession -Session $session
     
            Name Domain IsAdministrator IsAuthenticated
            ---- ------ --------------- ---------------
            sitecore\admin sitecore True False
            6/25/2015 11:09:17 AM
     
        .LINK
            Wait-RemoteScriptSession
 
        .LINK
            New-ScriptSession
 
        .LINK
            Stop-ScriptSession
    #>

   [CmdletBinding(SupportsShouldProcess = $true, DefaultParameterSetName="InProcess")]
    param(
        
        [Parameter(ParameterSetName='InProcess')]
        [Parameter(ParameterSetName='Session')]
        [Parameter(ParameterSetName='Uri')]
        [scriptblock]$ScriptBlock,

        [Parameter(ParameterSetName='Session')]
        [ValidateNotNull()]
        [pscustomobject]$Session,

        [Parameter(ParameterSetName='Uri')]
        [Uri[]]$ConnectionUri,

        [Parameter(ParameterSetName='Uri')]
        [string]$SessionId,

        [Parameter(ParameterSetName='Uri')]
        [string]$Username,

        [Parameter(ParameterSetName='Uri')]
        [string]$Password,

        [Parameter(ParameterSetName='Uri')]
        [string]$SharedSecret,

        [Parameter(ParameterSetName='Uri')]
        [System.Management.Automation.PSCredential]
        $Credential,
        
        [Parameter()]
        [Alias("ArgumentList")]
        [hashtable]$Arguments,

        [Parameter(ParameterSetName='Session')]
        [switch]$AsJob,
        
        [Parameter()]
        [switch]$Raw
    )

    if($PSCmdlet.MyInvocation.BoundParameters["WhatIf"].IsPresent) {
        $functionScriptBlock = {
            $WhatIfPreference = $true
        }
        $ScriptBlock = [scriptblock]::Create($functionScriptBlock.ToString() + $ScriptBlock.ToString());
    }
    $hasRedirectedMessages = $false
    if($PSCmdlet.MyInvocation.BoundParameters["Debug"].IsPresent -or $PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent) {
        $hasRedirectedMessages = $true
        $ScriptBlock = [scriptblock]::Create($writeStreamOverridesScript.ToString() + $ScriptBlock.ToString());
    }

    if($AsJob.IsPresent) {
        $nestedScript = $ScriptBlock.ToString()
        $ScriptBlock = [scriptblock]::Create("Start-ScriptSession -ScriptBlock { $($nestedScript) } -ArgumentList `$params | Select-Object -ExpandProperty ID")
    }

    $usingVariables = @(Get-UsingVariables -ScriptBlock $scriptBlock | 
        Group-Object -Property SubExpression | 
        ForEach-Object {
        $_.Group | Select-Object -First 1
    })
    
    $invokeWithArguments = $false        
    if ($usingVariables.count -gt 0) {
        $usingVar = $usingVariables | Group-Object -Property SubExpression | ForEach-Object {$_.Group | Select-Object -First 1}  
        Write-Debug "CommandOrigin: $($MyInvocation.CommandOrigin)"      
        $usingVariableValues = Get-UsingVariableValues -UsingVar $usingVar
        $invokeWithArguments = $true
    }

    if ($invokeWithArguments) {
        if(!$Arguments) { $Arguments = @{} }

        $paramsPrefix = "`$params."
        if($AsJob.IsPresent) {
            $paramsPrefix = "$"
        }
        $command = $ScriptBlock.ToString()
        foreach($usingVarValue in $usingVariableValues) {
            $Arguments[($usingVarValue.NewName.TrimStart('$'))] = $usingVarValue.Value
            $command = $command.Replace($usingVarValue.Name, "$($paramsPrefix)$($usingVarValue.NewName.TrimStart('$'))")
        }

        $newScriptBlock = $command
    } else {
        $newScriptBlock = $scriptBlock.ToString()
    }


    if($Arguments) {
        #This is still needed in order to pass types
        $parameters = ConvertTo-CliXml -InputObject $Arguments
    }

    if($PSCmdlet.ParameterSetName -eq "InProcess") {
        # TODO: This will likely fail for params.
        [scriptblock]::Create($newScriptBlock).Invoke()
    } else {
        if($PSCmdlet.ParameterSetName -eq "Session") {
            $Username = $Session.Username
            $Password = $Session.Password
            $SharedSecret = $Session.SharedSecret
            $SessionId = $Session.SessionId
            $Credential = $Session.Credential
            $UseDefaultCredentials = $Session.UseDefaultCredentials
            $ConnectionUri = $Session | ForEach-Object { $_.Connection.BaseUri }
            $PersistentSession = $Session.PersistentSession
        } else {
            $SessionId = [guid]::NewGuid()
            $PersistentSession = $false
        }
        
        $serviceUrl = "/-/script/script/?"
        $serviceUrl += "sessionId=" + $SessionId + "&rawOutput=" + $Raw.IsPresent + "&persistentSession=" + $PersistentSession
        foreach ($uri in $ConnectionUri) {            
            $url = $uri.AbsoluteUri.TrimEnd("/") + $serviceUrl
            $localParams = $parameters | Out-String
            
            #creating a psuedo file split on a special comment rather than trying to pass a potentially enormous set of data to the handler
            #theoretically this is the equivalent of a binary upload to the endpoint and breaking it into 2 files
            $body = "$($newScriptBlock)<#$($SessionId)#>$($localParams)"
            
            Write-Verbose -Message "Preparing to invoke the script against the service at url $($url)"
            Add-Type -AssemblyName System.Net.Http
            $handler = New-Object System.Net.Http.HttpClientHandler
            $handler.AutomaticDecompression = [System.Net.DecompressionMethods]::GZip -bor [System.Net.DecompressionMethods]::Deflate
            $client = New-Object -TypeName System.Net.Http.Httpclient $handler

            if(![string]::IsNullOrEmpty($SharedSecret)) {
                $token = New-Jwt -Algorithm 'HS256' -Issuer 'SPE Remoting' -Audience ($uri.GetLeftPart([System.UriPartial]::Authority)) -Name $Username -SecretKey $SharedSecret -ValidforSeconds 30
                $client.DefaultRequestHeaders.Authorization = New-Object System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", $token)
            } else {
                $authBytes = [System.Text.Encoding]::GetEncoding("iso-8859-1").GetBytes("$($Username):$($Password)")
                $client.DefaultRequestHeaders.Authorization = New-Object System.Net.Http.Headers.AuthenticationHeaderValue("Basic", [System.Convert]::ToBase64String($authBytes))
            }
                 
            if ($Credential) {
                $handler.Credentials = $Credential
            }

            if ($UseDefaultCredentials) {
                $handler.UseDefaultCredentials = $UseDefaultCredentials
            }
            
            [System.Net.HttpWebResponse]$script:errorResponse = $null 
            $script:encounteredError = $false

            $response = & {
                try {
                    Write-Verbose -Message "Transferring script to server"                 
                    $messageBytes = [System.Text.Encoding]::UTF8.GetBytes($body)
                    $ms = New-Object System.IO.MemoryStream
                    $gzip = New-Object System.IO.Compression.GZipStream($ms, [System.IO.Compression.CompressionMode]::Compress, $true)
                    $gzip.Write($messageBytes, 0, $messageBytes.Length)
                    $gzip.Close()
                    $ms.Position = 0
                    $content = New-Object System.Net.Http.ByteArrayContent(@(, $ms.ToArray()))
                    $ms.Close()
                    $content.Headers.ContentType = New-Object System.Net.Http.Headers.MediaTypeHeaderValue("text/plain")
                    $content.Headers.ContentEncoding.Add("gzip")
                   
                    $postResponse = $client.PostAsync($url, $content)
                    $taskResult = $postResponse.Result
                    if($taskResult) {
                        $taskResult.EnsureSuccessStatusCode() > $null
                        $taskResult.Content.ReadAsStringAsync().Result
                        Write-Verbose -Message "Script transfer complete."
                    } else {
                        $script:ex = $postResponse.Exception
                        $reason = $postResponse.Exception.Message
                        $innerException = $postResponse.Exception
                        while(($innerException = $innerException.InnerException)) {
                            $reason += " " + $innerException.Message                            
                        }
                        $script:encounteredError = $true
                        Write-Error -Message "Server response: $($reason)" -Category ConnectionError `
                            -CategoryActivity "Post" -CategoryTargetName $uri -CategoryReason "$($postResponse.Status)" -CategoryTargetType $RootPath -ErrorAction SilentlyContinue
                        $Host.UI.WriteErrorLine($reason)
                    }
                }
                catch [System.Net.Http.HttpRequestException] {
                    $script:ex = $_.Exception
                    [System.Net.Http.HttpResponseMessage]$script:errorResponse = $taskResult
                    if ($errorResponse) {
                        if ($errorResponse.StatusCode -eq [System.Net.HttpStatusCode]::Forbidden) {
                            Write-Verbose -Message "Check that the proper credentials are provided and that the service configurations are enabled."
                        }
                        elseif ($errorResponse.StatusCode -eq [System.Net.HttpStatusCode]::NotFound) {
                            Write-Verbose -Message "Check that the service files are properly configured."
                        }
                    }
                    else {
                        Write-Verbose -Message $ex.Message
                    }
                }
            }
            
            if ($errorResponse) {
                $script:encounteredError = $true
                Write-Error -Message "Server response: $($errorResponse.ReasonPhrase)" -Category ConnectionError `
                    -CategoryActivity "Download" -CategoryTargetName $uri -Exception ($script:ex) -CategoryReason "$($errorResponse.StatusCode)" -CategoryTargetType $RootPath 
            }
            
            if(!$encounteredError) {
                Write-Verbose -Message "Parsing response from server."
                Parse-Response -Response $response -HasRedirectedMessages $hasRedirectedMessages -Raw $Raw
            } else {
                Write-Verbose -Message "Stopping from further execution."
            }
        }
    }
}

function Invoke-RemoteScriptAsync {
    param(
        [Parameter()]
        [pscustomobject]$Session,

        [Parameter()]
        [scriptblock]$ScriptBlock,

        [Parameter()]
        [Alias("ArgumentList")]
        [hashtable]$Arguments,

        [Parameter()]
        [switch]$Raw
    )

    if($PSCmdlet.MyInvocation.BoundParameters["WhatIf"].IsPresent) {
        $functionScriptBlock = {
            $WhatIfPreference = $true
        }
        $ScriptBlock = [scriptblock]::Create($functionScriptBlock.ToString() + $ScriptBlock.ToString());
    }
    $hasRedirectedMessages = $false
    if($PSCmdlet.MyInvocation.BoundParameters["Debug"].IsPresent -or $PSCmdlet.MyInvocation.BoundParameters["Verbose"].IsPresent) {
        $hasRedirectedMessages = $true
        $ScriptBlock = [scriptblock]::Create($writeStreamOverridesScript.ToString() + $ScriptBlock.ToString());
    }

    $usingVariables = @(Get-UsingVariables -ScriptBlock $scriptBlock | 
        Group-Object -Property SubExpression | 
        ForEach {
        $_.Group | Select -First 1
    })
    
    $invokeWithArguments = $false        
    if ($usingVariables.count -gt 0) {
        $usingVar = $usingVariables | Group-Object -Property SubExpression | ForEach {$_.Group | Select -First 1}  
        Write-Debug "CommandOrigin: $($MyInvocation.CommandOrigin)"      
        $usingVariableValues = Get-UsingVariableValues -UsingVar $usingVar
        $invokeWithArguments = $true
    }

    if ($invokeWithArguments) {
        if(!$Arguments) { $Arguments = @{} }

        $paramsPrefix = "`$params."
        if($AsJob.IsPresent) {
            $paramsPrefix = "$"
        }
        $command = $ScriptBlock.ToString()
        foreach($usingVarValue in $usingVariableValues) {
            $Arguments[($usingVarValue.NewName.TrimStart('$'))] = $usingVarValue.Value
            $command = $command.Replace($usingVarValue.Name, "$($paramsPrefix)$($usingVarValue.NewName.TrimStart('$'))")
        }

        $newScriptBlock = $command
    } else {
        $newScriptBlock = $scriptBlock.ToString()
    }

    if($Arguments) {
        #This is still needed in order to pass types
        $parameters = ConvertTo-CliXml -InputObject $Arguments
    }

    $newScriptBlock = $scriptBlock.ToString()
    $Username = $Session.Username
    $Password = $Session.Password
    $SessionId = $Session.SessionId
    $Credential = $Session.Credential
    $UseDefaultCredentials = $Session.UseDefaultCredentials
    $ConnectionUri = $Session | ForEach-Object { $_.Connection.BaseUri }
    $PersistentSession = $Session.PersistentSession

    $serviceUrl = "/-/script/script/?"
    $serviceUrl += "sessionId=" + $SessionId + "&rawOutput=" + $Raw.IsPresent + "&persistentSession=" + $PersistentSession

    $handler = New-Object System.Net.Http.HttpClientHandler
    $handler.AutomaticDecompression = [System.Net.DecompressionMethods]::GZip -bor [System.Net.DecompressionMethods]::Deflate
    $client = New-Object -TypeName System.Net.Http.Httpclient $handler
    $authBytes = [System.Text.Encoding]::GetEncoding("iso-8859-1").GetBytes("$($Username):$($Password)")
    $client.DefaultRequestHeaders.Authorization = New-Object System.Net.Http.Headers.AuthenticationHeaderValue("Basic", [System.Convert]::ToBase64String($authBytes))
       
    if ($Credential) {
        $handler.Credentials = $Credential
    }

    if($UseDefaultCredentials) {
        $handler.UseDefaultCredentials = $UseDefaultCredentials
    }
   
    $localParams = $parameters | Out-String

    $messageBytes = [System.Text.Encoding]::UTF8.GetBytes("$($newScriptBlock.ToString())<#$($SessionId)#>$($localParams)")

    $ms = New-Object System.IO.MemoryStream
    $gzip = New-Object System.IO.Compression.GZipStream($ms, [System.IO.Compression.CompressionMode]::Compress, $true)
    $gzip.Write($messageBytes, 0, $messageBytes.Length)
    $gzip.Close()
    $ms.Position = 0
    $content = New-Object System.Net.Http.ByteArrayContent(@(,$ms.ToArray()))
    $ms.Close()
    $content.Headers.ContentType = New-Object System.Net.Http.Headers.MediaTypeHeaderValue("text/plain")
    $content.Headers.ContentEncoding.Add("gzip")

    foreach($uri in $ConnectionUri) {
        $url = $uri.AbsoluteUri.TrimEnd("/") + $serviceUrl

        $taskPost = $client.PostAsync($url, $content)

        $localProps = @{
            Raw = $Raw.IsPresent
        }
        $continuation = New-RunspacedDelegate ([Func[System.Threading.Tasks.Task[System.Net.Http.HttpResponseMessage],object, PSObject]] { 
            param($t,$props)

            $contentTask = $t.Result.Content.ReadAsStringAsync()
            $response = $contentTask.GetAwaiter().GetResult()
            Parse-Response -Response $response -HasRedirectedMessages $false -Raw $props.Raw
        })
        Invoke-GenericMethod -InputObject $taskPost -MethodName ContinueWith -GenericType PSObject -ArgumentList $continuation,$localProps
    }    
}