PSeudo.psm1

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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
# MIT License (Expat)
#
# Copyright (c) 2020 Josh Holbrook
# Copyright (c) 2014 msumimz
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

function Get-Base64String {
  <#
  .Description
  The Get-Base64String function converts a string into bytes and then into a
  base64 string. Note that this encoding is based on a UTF-16 LE byte
  encoding, rather tha UTF-8.
 
  .Parameter String
  An unencoded string to convert to base64.
 
  .Outputs
  string. A base64 encoded string.
  #>


  param(
    [string]$String
  )

  $Bytes = [System.Text.Encoding]::Unicode.GetBytes($String)
  [Convert]::ToBase64String($Bytes)
}

$Formatter = New-Object System.Runtime.Serialization.Formatters.Binary.BinaryFormatter

function Test-Serializable {
  <#
  .Description
  The Test-Serializable function tests an object to see if it's serializable
  with .NET's serialization framework. It does this by attempting to serialize
  the object into a MemoryStream. This means that an object may be serialized
  twice - once to test that it's serializable and then a second time to "do it
  for real" - but it seems to be the most straightforward and accurate way of
  ascertaining this property in PowerShell.
 
  .Parameter InputObject
  An object to test for serializability.
 
  .Outputs
  boolean. True if the object is serializable and false if not.
  #>


  param(
    $InputObject
  )

  $IsSerializable = $true

  if ($InputObject) {
    try {
      $FormattedString = New-Object System.IO.MemoryStream
      $Formatter.Serialize($FormattedString,$InputObject)
    } catch [System.Runtime.Serialization.SerializationException]{
      $IsSerializable = $false
    }
  }

  return $IsSerializable
}

function ConvertTo-Representation {
  <#
  .Description
  The ConvertTo-Representation function converts an input object into a
  deserializable base64 representation. This is so that we can send objects
  over command line arguments from the host process into the Administrator
  process. When objects support .NET's serialization framework this is fully
  reversible; in other cases, we create a new PSObject with the same top-
  level properties (unless they're non-serializable, in which case they are
  stubbed with a string representation). This means that an object
  representation, though one with a significant loss of fidelity, can still be
  deserialized later.
 
  .Parameter InputObject
  An object to convert to a base64 representation.
 
  .Outputs
  string. A base64 string that can be deserialized by
  ConvertFrom-Representation inside the Administrator process.
  #>


  param(
    $InputObject
  )

  $SerializableObject = $InputObject

  if (-not (Test-Serializable $InputObject)) {
    $SerializableObject = New-Object PSObject

    @('Property','NoteProperty') | ForEach-Object {
      $InputObject | Get-Member -MemberType $_ | ForEach-Object {
        $Name = $_.Name
        $Value = ($InputObject | Select-Object -ExpandProperty $Name)
        if (Test-Serializable $Value) {
          $SerializableObject | Add-Member $Name $Value
        } else {
          $SerializableObject | Add-Member $Name ([string]$Value)
        }
      }
    }
  }

  $FormattedString = New-Object System.IO.MemoryStream
  $Formatter.Serialize($FormattedString,$SerializableObject)
  $Bytes = New-Object byte[] ($FormattedString.length)
  [void]$FormattedString.Seek(0,"Begin")
  [void]$FormattedString.Read($Bytes,0,$FormattedString.length)
  [Convert]::ToBase64String($Bytes)
}


$DeserializerString = @'
function ConvertFrom-Representation {
  param(
    [string]$Representation
  )
 
  $Formatter = New-Object System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
  $Bytes = [Convert]::FromBase64String($Representation)
  $FormattedString = New-Object System.IO.MemoryStream
  [void]$FormattedString.Write($Bytes,0,$Bytes.length)
  [void]$FormattedString.Seek(0,"Begin")
  $Formatter.Deserialize($FormattedString)
}
'@


$SerializerString = @'
function Test-Serializable {
  param(
    $InputObject
  )
 
  $IsSerializable = $true
 
  if ($InputObject) {
    try {
      $FormattedString = New-Object System.IO.MemoryStream
      $Formatter.Serialize($FormattedString,$InputObject)
    } catch [System.Runtime.Serialization.SerializationException]{
      $IsSerializable = $false
    }
  }
 
  return $IsSerializable
}
 
function New-SerializableObject {
  [CmdletBinding(SupportsShouldProcess,ConfirmImpact = 'Low')]
  param(
    [object]$InputObject
  )
 
  if ($InputObject -eq $null) {
    return $InputObject
  }
 
  $SerializableObject = $InputObject
 
  if (-not (Test-Serializable $InputObject) -and $PSCmdlet.ShouldProcess($InputObject,'Create a new object')) {
    $SerializableObject = New-Object PSObject
    @('Property','NoteProperty') | ForEach-Object {
      $InputObject | Get-Member -MemberType $_ | ForEach-Object {
        $Name = $_.Name
        $Value = ($InputObject | Select-Object -ExpandProperty $Name)
        if (Test-Serializable $Value) {
          $SerializableObject | Add-Member $Name $Value
        } else {
          $SerializableObject | Add-Member $Name ([string]$Value)
        }
      }
    }
  }
 
  return $SerializableObject
}
 
'@


$SenderString = @'
function Send-Message {
  [CmdletBinding()]
  param(
    [string]$Type,
 
    [Parameter(ValueFromPipeline = $true)]
    [object]$InputObject
  )
 
  $SerializableObject = New-SerializableObject $InputObject
 
  $Payload = @{ Type = $Type; Object = $SerializableObject }
 
  $OutPipe.WriteByte(1)
  $Formatter.Serialize($OutPipe,$Payload)
}
 
filter Send-ToPipe {
  if ($CapturedStream -eq 2 -and ($_ -is [System.Management.Automation.ErrorRecord])) {
    Send-Error -ErrorRecord $_
  } elseif ($CapturedStream -eq 3 -and ($_ -is [System.Management.Automation.WarningRecord])) {
    Send-Warning $_.Message
  } elseif ($CapturedStream -eq 4 -and ($_ -is [System.Management.Automation.VerboseRecord])) {
    Send-Verbose $_.Message
  } elseif ($CapturedStream -eq 5 -and ($_ -is [System.Management.Automation.DebugRecord])) {
    Send-Debug $_.Message
  } elseif ($CapturedStream -eq 6 -and ($_ -is [System.Management.Automation.InformationRecord])) {
    Send-Information $_.MessageData $_.Tags
  } else {
    Send-Message -Type 'Output' -InputObject $_
  }
}
 
function Send-Output {
  [CmdletBinding()]
  param(
    [Parameter(ValueFromPipeline = $true,Mandatory = $true)]
    [object]$InputObject,
 
    [switch]$NoEnumerate
  )
 
  $Cmd = (Get-Command 'Write-Output' -CommandType Cmdlet)
 
  & $Cmd -InputObject $InputObject -NoEnumerate:$NoEnumerate | Send-ToPipe
}
 
function Send-Error {
  [CmdletBinding(PositionalBinding = $false)]
  param(
    [Parameter(ParameterSetName = 'Exception')]
    [Exception]$Exception,
 
    [Parameter(Mandatory = $true,ParameterSetName = 'ErrorRecord')]
    [System.Management.Automation.ErrorRecord]$ErrorRecord,
 
    [Parameter(Position = 0,ParameterSetName = 'Exception')]
    [string]$Message,
 
    [Parameter(Position = 1,ParameterSetName = 'Exception')]
    [System.Management.Automation.ErrorCategory]$Category = [System.Management.Automation.ErrorCategory]'NotSpecified',
 
    [Parameter(Position = 2,ParameterSetName = 'Exception')]
    [string]$ErrorId,
 
    [Parameter(Position = 3,ParameterSetName = 'Exception')]
    [Object]$TargetObject,
 
    [Parameter(Position = 4)]
    [string]$RecommendedAction,
 
    [Parameter(Position = 5)]
    [string]$CategoryActivity,
 
    [Parameter(Position = 6)]
    [string]$CategoryReason,
 
    [Parameter(Position = 7)]
    [string]$CategoryTargetName,
 
    [Parameter(Position = 8)]
    [string]$CategoryTargetType
  )
 
  if ($Message -and -not $Exception) {
    $Exception = New-Object Exception $Message
  }
 
  if ($Exception) {
    $ErrorRecord = New-Object System.Management.Automation.ErrorRecord @(
      $Exception,
      $ErrorId,
      $Category,
      $TargetObject
    )
  }
 
  $Payload = @{
    ErrorRecord = $ErrorRecord;
    RecommendedAction = $RecommendedAction;
    CategoryActivity = $CategoryActivity;
    CategoryReason = $CategoryReason;
    CategoryTargetName = $CategoryTargetName;
    CategoryTargetType = $CategoryTargetType
  }
 
  Send-Message -Type Error -InputObject $Payload
}
 
function Send-Fatal {
  param(
    [System.Management.Automation.ErrorRecord]$ErrorRecord
  )
 
  Send-Message -Type Fatal -InputObject $ErrorRecord
}
 
function Send-Debug {
  param(
    [string]$Message
  )
 
  Send-Message -Type Debug -InputObject $Message
}
 
function Send-Verbose {
  param(
    [string]$Message
  )
 
  Send-Message -Type Verbose -InputObject $Message
}
 
function Send-Warning {
  param(
    [string]$Message
  )
 
  Send-Message -Type Warning -InputObject $Message
}
 
function Send-Information {
  param(
    [object]$MessageData,
    [string[]]$Tags = @()
  )
 
  Send-Message -Type Information -InputObject @{
    MessageData = (New-SerializableObject $MessageData);
    Tags = $Tags
  }
}
 
function Send-Host {
  param(
    [object]$Object,
    [switch]$NoNewLine,
    [object]$Separator = '',
    [ConsoleColor]$ForegroundColor,
    [ConsoleColor]$BackgroundColor
  )
 
  Send-Message -Type Host -InputObject @{
    Object = (New-SerializableObject $Object);
    NoNewLine = $NoNewLine.IsPresent;
    Separator = (New-SerializableObject $Separator);
    ForegroundColor = $ForegroundColor;
    BackgroundColor = $BackgroundColor
  }
}
 
function Send-Progress {
  [CmdletBinding(PositionalBinding = $false)]
  param(
    [Parameter(Position = 0,Mandatory = $true)]
    [string]$Activity,
 
    [Parameter(Position = 1)]
    [string]$Status,
 
    [Parameter(Position = 2)]
    [int]$Id,
 
    [int]$PercentComplete,
    [int]$SecondsRemaining,
    [string]$CurrentOperation,
    [int]$ParentId,
    [switch]$Completed,
    [int]$SourceId
  )
 
  Send-Message -Type Progress -InputObject @{
    Activity = $Activity;
    Status = $Status;
    Id = $Id;
    PercentComplete = $PercentComplete;
    SecondsRemaining = $SecondsRemaining;
    CurrentOperation = $CurrentOperation;
    ParentId = $ParentId;
    Completed = $Completed.IsPresent;
    SourceId = $SourceId
  }
}
 
Set-Alias -Name Write-Output -Value Send-Output
Set-Alias -Name Write-Error -Value Send-Error
Set-Alias -Name Write-Debug -Value Send-Debug
Set-Alias -Name Write-Verbose -Value Send-Verbose
Set-Alias -Name Write-Warning -Value Send-Warning
Set-Alias -Name Write-Information -Value Send-Information
Set-Alias -Name Write-Host -Value Send-Host
Set-Alias -Name Write-Progress -Value Send-Progress
'@


$RunnerString = @'
$Formatter = New-Object System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
 
Set-Location $Location
 
try {
  try {
    $OutPipe = New-Object System.IO.Pipes.NamedPipeClientStream ".",$PipeName,"Out"
    $OutPipe.Connect()
 
    if ($ArgumentList.length -eq 0 -and $Command -is [string]) {
      if ($CapturedStream -eq 2) {
        Invoke-Expression -Command $Command 2>&1 | Send-ToPipe
      } elseif ($CapturedStream -eq 3) {
        Invoke-Expression -Command $Command 3>&1 | Send-ToPipe
      } elseif ($CapturedStream -eq 4) {
        Invoke-Expression -Command $Command 4>&1 | Send-ToPipe
      } elseif ($CapturedStream -eq 5) {
        Invoke-Expression -Command $Command 5>&1 | Send-ToPipe
      } elseif ($CapturedStream -eq 6) {
        Invoke-Expression -Command $Command 6>&1 | Send-ToPipe
      } else {
        Invoke-Expression -Command $Command | Send-ToPipe
      }
    } elseif ($CapturedStream -eq 2) {
      & $Command @ArgumentList 2>&1 | Send-ToPipe
    } elseif ($CapturedStream -eq 3) {
      & $Command @ArgumentList 3>&1 | Send-ToPipe
    } elseif ($CapturedStream -eq 4) {
      & $Command @ArgumentList 4>&1 | Send-ToPipe
    } elseif ($CapturedStream -eq 5) {
      & $Command @ArgumentList 5>&1 | Send-ToPipe
    } elseif ($CapturedStream -eq 6) {
      & $Command @ArgumentList 6>&1 | Send-ToPipe
    } else {
      & $Command @ArgumentList | Send-ToPipe
    }
  } catch [Exception]{
    Send-Fatal $_
  }
} finally {
  $OutPipe.WriteByte(0)
  $OutPipe.WaitForPipeDrain()
  $OutPipe.Close()
}
'@


function Test-CommandString {
  <#
  .Description
  Test that a command string will successfully parse by PowerShell such that
  it can be ran as the -Command for a PowerShell child process. This is
  important to catch ahead of time because if the parent process waits for a
  connection that will never come it will hang indefinitely.
 
  .Parameter Command
  A string intended to be executed by PowerShell.
  #>


  [CmdletBinding()]
  param(
    [string]$Command
  )

  $Tokens = $null
  $ParseErrors = $null

  [System.Management.Automation.Language.Parser]::ParseInput($Command,[ref]$Tokens,[ref]$ParseErrors) | Out-Null

  if ($ParseErrors) {
    $Exception = New-Object Exception $ParseErrors[0].Message
    $ErrorRecord = New-Object System.Management.Automation.ErrorRecord @(
      $Exception,
      $ParseErrors[0].ErrorId,
      [System.Management.Automation.ErrorCategory]::'ParserError',
      $Command
    )
    $PSCmdlet.ThrowTerminatingError($ErrorRecord)
  }
}

function Invoke-AdminProcess {
  <#
  .Description
  Run the Administrator process with the given command string, file
  path and verb. This function is exposed internally so that it can be
  easily mocked in tests.
 
  .Parameter CommandString
  A string intended to be executed by PowerShell.
 
  .Parameter FilePath
  The path to the PowerShell executable.
 
  .Parameter Verb
  The verb to use when starting the process. Typically "RunAs".
 
  .Outputs
 
  None.
  #>


  param(
    [string]$CommandString,
    [string]$FilePath,
    [string]$Verb
  )

  $ProcStartInfo = New-Object System.Diagnostics.ProcessStartInfo
  $ProcStartInfo.FileName = $FilePath
  $ProcStartInfo.Verb = $Verb

  if ($env:INVOKEASADMINDEBUG) {
    $ProcStartInfo.Arguments = "-NoExit","-EncodedCommand",(Get-Base64String $CommandString)
  } else {
    $ProcStartInfo.WindowStyle = "Hidden"
    $ProcStartInfo.Arguments = "-EncodedCommand",(Get-Base64String $CommandString)
  }

  $Process = [System.Diagnostics.Process]::Start($ProcStartInfo)

  [void]$Process
}

function Invoke-AsAdministrator {
<#
  .Synopsis
  Execute commands with elevated Administrator privileges.
 
  .Description
  The Invoke-AsAdministrator function executes a command as an elevated user.
 
  It does this by creating a child process running with Administrator
  privileges and passing it a special command. This command encodes the
  arguments to the Invoke-AsAdministrator function using .NET's serialization
  framework and a base64 encoding. It then creates a named pipe to initiate
  a connection back to the child process, with which it sends output from
  the commands being invoked - again using .NET's serialization framework -
  back to the host process. This allows us to execute commands in an
  Administrator-level process and have the output accessible in the host
  terminal, "just like sudo".
 
  Additionally, it defines a number of functions and shadowing aliases for
  common output commands:
 
  - Write-Output
  - Write-Error
  - Write-Debug
  - Write-Verbose
  - Write-Warning
  - Write-Information
  - Write-Host
  - Write-Progress
 
  Naive calls to these commands will be captured and their corresponding
  parameters will be sent to the host process, where the corresponding "real"
  command will be called.
 
  .Parameter ScriptBlock
  When defined, this gets evaluated in the Administrator process with the
  call operator (&).
 
  .Parameter Command
  When defined, this gets evaluated in the Administrator process with
  Invoke-Expression.
 
  .Parameter ArgumentList
  Arguments to be passed to the script block.
 
  .Parameter FilePath
  An optional path to a PowerShell executable. This defaults to the
  executable being used to run the parent process; however it can be
  overridden to run the Administrator process with a different
  executable than the one currently running.
 
  .Parameter Verb
  In addition to the RunAs verb, exes also support the RunAsUser verb. This
  allows for using this alternate verb.
 
  .Parameter CapturedStream
  By default, the 'error' stream (stream 2) is completely captured and all
  ErrorRecords are re-emitted on the host Error stream. This allows for
  capturing errors that are emitted by calling $PSCmdlet.WriteError or by
  native cmdlets.
 
  This value can be set to capture other streams. For example,
  setting this value to 6 would capture all data emitted over the Information
  stream. This behavior can be completely disabled by setting this value to 1
  (the output stream).
 
  .Example
  Invoke-AsAdministrator { "hello world!" }
 
  This will execute a script block as Administrator and output the string
  "hello world!".
 
  .Example
  Invoke-AsAdministrator '"hello world!"'
 
  This will evaluate a string as Administrator and output the string
  "hello world!".
 
  .Example
  Invoke-AsAdministrator { param($Friend) "hello $Friend!" } -ArgumentList 'Korben'
 
  This will execute a script block as Administrator and pass an argument to
  it, outputting the string "hello Korben!".
 
  .Example
  Invoke-AsAdministrator { $Env:AppData }
 
  This will output the host user's AppData directory. Variables in script
  blocks are evaluated before they're ran in the Administrator process.
 
  .Example
  Invoke-AsAdministrator { throw 'baby' }
 
  This will throw an exception on the host process. Exceptions are captured
  and proxied.
 
  .Example
  Invoke-AsAdministrator { Write-Error 'this is a test error!'; Write-Information 'this is some IMPORTANT INFORMATION!'; Write-Host "I'm writing to your host!" } 6>&1
 
  This will write an error to the host error stream, information to the
  information stream (redirected to the output stream on the host), and
  write a message directly to the host. The functions Write-Output,
  Write-Debug, Write-Verbose, Write-Warning and Write-Progress work
  similarly.
 
  .Example
  Invoke-AsAdministrator { Get-Process -IncludeUsername | Sort-Object -Property VM -Descending | Select-Object -First 1 }
 
  This will get all processes, including processes not owned by the user -
  which is information only accessible to the Administrator - and then find
  the one using the most memory, finally sending data back to the host
  output stream. Process objects are non-serializable, so the object returned
  by Invoke-AsAdministrator is a PSObject with the same properties.
 
  .Link
  about_Pseudo
 
  .Link
  about_PSeudo_Administrator_Scope
 
  .Link
  https://github.com/jfhbrook/PSeudo
  #>


  [CmdletBinding()]
  param(
    [Parameter(Position = 0,Mandatory = $true,ParameterSetName = 'ScriptBlock')]
    [scriptblock]$ScriptBlock,

    [Parameter(Position = 0,Mandatory = $true,ParameterSetName = 'StringCommand')]
    [string]$Command,

    [Parameter(Position = 1,Mandatory = $false,ParameterSetName = 'ScriptBlock')]
    [object[]]$ArgumentList,

    [Parameter(Mandatory = $false)]
    [string]$FilePath = [Diagnostics.Process]::GetCurrentProcess().Path,

    [Parameter(Mandatory = $false)]
    [string]$Verb = 'RunAs',

    [Parameter(Mandatory = $false)]
    [ValidateRange(1,6)]
    [int]$CapturedStream = 2
  )

  Set-StrictMode -Version Latest

  $PipeName = "AdminPipe-" + [guid].GUID.ToString()

  $Location = ConvertTo-Representation (Get-Location).Path

  if ($ScriptBlock) {
    $RemoteCommand = ConvertTo-Representation $ScriptBlock
  } else {
    Test-CommandString $Command
    $RemoteCommand = ConvertTo-Representation $Command
  }

  $CommandString = "
  $DeserializerString
 
  `$PipeName = `'$PipeName`'
 
  `$Location = ConvertFrom-Representation `'$Location`'
 
  `$Command = ConvertFrom-Representation `'$RemoteCommand`'
  "


  if ($ArgumentList) {
    $RemoteArgs = ConvertTo-Representation $ArgumentList
    $CommandString += "`$ArgumentList = @(ConvertFrom-Representation `'$RemoteArgs`')`n"
  } else {
    $CommandString += "`$ArgumentList = @()`n"
  }

  $CommandString += "
  `$CapturedStream = $CapturedStream
 
  $SerializerString
 
  $SenderString
 
  $RunnerString
  "


  Test-CommandString $CommandString

  $InPipe = New-Object System.IO.Pipes.NamedPipeServerStream $PipeName,"In" -ErrorAction Stop

  Invoke-AdminProcess $CommandString -FilePath $FilePath -Verb $Verb

  $InPipe.WaitForConnection()

  try {
    for (;;) {
      $Type = $InPipe.ReadByte()
      if ($Type -eq 0) {
        break
      }

      $Payload = $Formatter.Deserialize($InPipe)
      $PayloadType = $Payload.Type
      $Object = $Payload.Object

      switch ($PayloadType) {
        'Output' {
          Write-Output $Object
        }
        'Error' {
          Write-Error `
             -ErrorRecord $Object.ErrorRecord `
             -RecommendedAction $Object.RecommendedAction `
             -CategoryActivity $Object.CategoryActivity `
             -CategoryReason $Object.CategoryReason `
             -CategoryTargetName $Object.CategoryTargetName `
             -CategoryTargetType $Object.CategoryTargetType
        }
        'Fatal' {
          $PSCmdlet.ThrowTerminatingError($Object)
        }
        'Debug' {
          Write-Debug $Object
        }
        'Verbose' {
          Write-Verbose $Object
        }
        'Warning' {
          Write-Warning $Object
        }
        'Information' {
          Write-Information -MessageData $Object.MessageData -Tags $Object.Tags
        }
        'Host' {
          $Splatted = @{}

          $Object.GetEnumerator() |
          Where-Object { $_.Value } |
          ForEach-Object { $Splatted[$_.Name] = $_.Value } | Out-Null

          Write-Host @Splatted
        }
        'Progress' {
          $Splatted = @{}

          $Object.GetEnumerator() |
          Where-Object { $_.Value } |
          ForEach-Object { $Splatted[$_.Name] = $_.Value } | Out-Null

          Write-Progress @Splatted | Out-Null
        }
        default {
          $Exception = New-Object Exception "Invalid message type $PayloadType"
          $ErrorRecord = New-Object System.Management.Automation.ErrorRecord @(
            $Exception,
            'InvalidMessageTypeError',
            [System.Management.Automation.ErrorCategory]'InvalidData',
            $Payload
          )
          $PSCmdlet.WriteError($ErrorRecord)
        }
      }
    }
  } catch {
    $PSCmdlet.WriteError($_)
  } finally {
    $InPipe.Close()
  }
}

Export-ModuleMember `
   -Function @(
  'Get-Base64String',
  'ConvertTo-Representation',
  'Invoke-AdminProcess',
  'Invoke-AsAdministrator',
  'Test-CommandString'
) `
   -Variable @(
  'DeserializerString',
  'SerializerString',
  'SenderString',
  'RunnerString'
)