Sintez.Module.RDS.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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
################################################################################
# Copyright 2017 Sergey Rusak, Heavenbay.ru
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
################################################################################

# Reset vars:
[string]$Broker = ""
[PSCredential]$Credential = [System.Management.Automation.PSCredential]::Empty

# Associate digitals in user session status to words:
function getStateName([int]$StateId) {

    [string]$rez = "###";
    switch ($StateId)
    {
    0 {$rez = "Active"}
    1 {$rez = "Active, Minimized"}
    2 {$rez = "Query"}
    3 {$rez = "Shadow"}
    4 {$rez = "Disconnected"}
    5 {$rez = "Idle"}
    6 {$rez = "Listen"}
    7 {$rez = "Reset"}
    8 {$rez = "Down"}
    9 {$rez = "Init"}
    default {$rez = "Invalid State"}
    }
    return $rez
}

# Associate collection names from aliases to fullnames and make table with host/fullname.
function SelectCollections ([PSCredential]$Credential,[string]$Broker) {

    $col = @{}
    $newCol = @{}
    
    Try {
        Get-WmiObject -Credential $Credential -ComputerName $Broker -Query "SELECT Alias, Name FROM Win32_RDSHCollection" -Namespace root\CIMv2\rdms | %{$col.Add($_.alias, $_.name)}
    }
    Catch [System.UnauthorizedAccessException] {
        Write-Host "Access to a remote broker is denided. Start cmdlet with a key '-C' to set the right credentials." -BackgroundColor Black -ForegroundColor Red
        Write-Host ""
        Break
    }
    Catch [System.Runtime.InteropServices.COMException] {
        Write-Host "Broker is unavailable. Probably wrong IP/FQDN or firewall issues." -BackgroundColor Black -ForegroundColor Red
        Write-Host ""
        Break
    }

    Get-WmiObject -Credential $Credential -ComputerName $Broker -Query "SELECT Name, CollectionAlias FROM Win32_RDSHServer" -Namespace root\CIMv2\rdms | %{$newCol.Add(($_.Name),$col[$_.CollectionAlias])}

    return $newCol
}

# Create user list table with GUI
function CreateUsersList ([PSCredential]$Credential,[string]$Broker,[array]$newCol) {
    Get-WmiObject -Credential $Credential -ComputerName $Broker -Namespace "root\CIMv2" -Query "SELECT UserName,IdleTime,CreateTime,HostServer,DomainName,SessionState,UnifiedSessionID FROM Win32_SessionDirectorySessionEx" `
    | Select UserName,`
    @{Label="SID";Expression={$_.UnifiedSessionID}},`
    @{Label="Host";Expression={$_.HostServer}},`
    @{Label="Activity";Expression={getStateName($_.SessionState)}},`
    @{Label="Collection";Expression={$newCol[$_.HostServer]}},`
    @{Label="Creation Time";Expression={[datetime]::ParseExact(($_.CreateTime -replace "\..*",""),"yyyyMMddHHmmss", $null)}},`
    @{Label="Domain";Expression={$_.DomainName}},`
    @{Label="Idle";Expression={"{0:N0}" -f ([timespan]::frommilliseconds($_.IdleTime)).TotalMinutes}} `
    | Sort UserName `
    | Out-GridView -PassThru -Title "RDS Sessions" `
    | SessionAction
}

function Install-RDSServer {


<#
    .SYNOPSIS
    Install-RDSServer [[-RDSH] <Array[]>] [[-Domain] <String[]>] [[-Group] <String[]>] [-View] [-Remove] [-Credential]
 
    .DESCRIPTION
    Add/Remove user/group to RDP-Tcp administrator group settings on server side (ONLY RDSH servers). By default only users from Administrators group are able to make changes on RDP-Tcp connections. If you want to grant access to another group you have to create a new group in AD and add it to Security ACLs. This script will add it for you.
 
    This script MUST be started as local Administrator.
      
    .PARAMETER RDSH
    -RDSH [-SH] - Execute commands on the specified computers. The default is the local computer. Type the NetBIOS name, an IP address, or a fully qualified domain name (FQDN) of a remote computer. To specify the local computer, type the computer name, a dot (.), or localhost.
 
    .PARAMETER Domain
    -Domain [-D] - NetBIOS domain name. For domain.com it should be just DOMAIN.
 
    .PARAMETER Group
    -Group [-G] - Group of users who allow to connect (shadow) to the user session.
 
    .PARAMETER View
    -View [-V] - Show all groups from RDP-Tcp security settings tab.
 
    .PARAMETER Remove
    -Remove [-R] - Clear all custom groups in RDP-Tcp security ACLs (reset param).
 
    .PARAMETER Credential
    -Credential [-C] - Credentials switch. Enforce credential form.
 
    .EXAMPLE
    # Add RDS security group with administrator rights (Shadow, Logoff, Disconnect and etc.) to local RDSH server. If you add group you also have to set DOMAIN param. And vice versa:
    Install-RDSServer -Domain DOMAIN -Group rds_support_team
 
    .EXAMPLE
    # As in example #1 we add RDS security group to remote RDSH servers:
    Install-RDSServer -SH RDSH1,RDSH2,RDSH3 -Domain DOMAIN -Group rds_support_team
 
    .EXAMPLE
    # Clear all custom groups in RDP security settings on local RDSH server:
    Install-RDSServer -R
 
    .EXAMPLE
    # Show all groups in RDP-Tcp security settings on remote RDSH servers. Param "-C" tells cmdlet launch credential prompt window before script will continue:
    Install-RDSServer -View -SH RDSH1,RDSH2,RDSH3 -C
 
    .LINK
    http://www.heavenbay.ru/app/sintez/help/module/rds#installserver
#>



    [CmdletBinding()]
    Param(
        [alias("SH")]
        [array]$RDSH,

        [alias("D")]
        [string]$Domain,
    
        [alias("G")]
        [string]$Group,

        [alias("R")]
        [switch]$Remove,
        [alias("V")]
        [switch]$View,
        [alias("C")]
        [switch]$Credential
    )

    $ErrorActionPreference = "stop"

    if (!$RDSH) {[array]$RDSH = $ENV:COMPUTERNAME}

    if ($Credential -eq $true) {
        [PSCredential]$Credential = Get-Credential
    } else {
        [PSCredential]$Credential = [System.Management.Automation.PSCredential]::Empty
    }

    if ($Remove -eq $true) {
        foreach ($SH in $RDSH) {
            Write-Host ""
            Write-Host "Server is $SH`:"
            Try {
                ((gwmi -ComputerName $SH -Credential $Credential -Namespace "root\CIMV2\TerminalServices" -Class Win32_TSPermissionsSetting).where({$_.TerminalName -eq "RDP-Tcp"})).RestoreDefaults() | Out-Null
                If (!$Error) {Write-Host "Done" -BackgroundColor Black -ForegroundColor Green}
            }
            Catch [System.Management.Automation.MethodInvocationException] {
                Write-Host "Check that RDS-RD-Server role is installed on this PC." -BackgroundColor Black -ForegroundColor Red
            }
            Catch [System.Runtime.InteropServices.COMException] {
                Write-Host "RDSH is unavailable. Probably wrong IP/FQDN or firewall issues." -BackgroundColor Black -ForegroundColor Red
            }
            Catch [System.UnauthorizedAccessException] {
                Write-Host "Access to a remote broker is denided. Start cmdlet with a key '-C' to set the right credentials." -BackgroundColor Black -ForegroundColor Red
                Write-Host ""
                Break
            }

        }

        Write-Host ""
        Write-Host "Complited!"
        Write-Host ""
        break
    }

    if ($View -eq $true) {
        foreach ($SH in $RDSH) {
            Write-Host ""
            Write-Host "Server is $SH`:"
            Try {
                $v = ((gwmi -ComputerName $SH -Credential $Credential -Namespace "root\CIMV2\TerminalServices" -Class Win32_TSPermissionsSetting).where({$_.TerminalName -eq "RDP-Tcp"})).StringSecurityDescriptor
                [regex]::matches($v, "S-1-5-\d+-\d+-\d+-\d+-\d+").Groups.Value | %{Write-Host (New-Object System.Security.Principal.SecurityIdentifier($_)).Translate([System.Security.Principal.NTAccount]).Value -ForegroundColor Yellow -BackgroundColor Black}
            }
            Catch [System.Management.Automation.PSArgumentException] {
                Write-Host "There are no groups." -ForegroundColor Yellow -BackgroundColor Black
            }
            Catch [System.Runtime.InteropServices.COMException] {
                Write-Host "RDSH is unavailable. Probably wrong IP/FQDN or firewall issues." -BackgroundColor Black -ForegroundColor Red
            }
            Catch [System.UnauthorizedAccessException] {
                Write-Host "Access to a remote broker is denided. Start cmdlet with a key '-C' to set the right credentials." -BackgroundColor Black -ForegroundColor Red
                Write-Host ""
                Break
            }

        }

        Write-Host ""
        Write-Host "Complited!"
        Write-Host ""
        break
    }

    $Group = $Domain + "\" + $Group
    foreach ($SH in $RDSH) {
        Write-Host ""
        Write-Host "Server is $SH`:"
        Try {
            ((gwmi -ComputerName $SH -Credential $Credential -Namespace "root\CIMV2\TerminalServices" -Class Win32_TSPermissionsSetting).where({$_.TerminalName -eq "RDP-Tcp"})).AddAccount($Group,2) | Out-Null
            If (!$Error) {Write-Host "Done" -BackgroundColor Black -ForegroundColor Green}
        }
        Catch [System.Runtime.InteropServices.COMException] {
            Write-Host "RDSH is unavailable. Probably wrong IP/FQDN or firewall issues." -BackgroundColor Black -ForegroundColor Red
        }
        Catch [System.Management.Automation.MethodInvocationException] {
            Write-Host "Wrong domain/group. Please restart script with right params." -ForegroundColor Red -BackgroundColor Black
            Break
        }
        Catch [System.UnauthorizedAccessException] {
            Write-Host "Access to a remote broker is denided. Start cmdlet with a key '-C' to set the right credentials." -BackgroundColor Black -ForegroundColor Red
            Write-Host ""
            Break
        }
    }

    Write-Host ""
    Write-Host "Complited!"
    Write-Host ""

}

function Install-RDSClient {


<#
    .SYNOPSIS
    Install-RDSClient [-Remove]
 
    .DESCRIPTION
    Add/Remove registry tree "rdsmc" and .js file (WINDIR) for SINTEZ App RDS module on client PC.
 
    This script MUST be started as local Administrator.
  
    .PARAMETER Remove
    -Remove [-R] - Uninstall changes.
 
    .EXAMPLE
    # Install RDS module settings on support team PC:
    Install-RDSClient
 
    .EXAMPLE
    # Remove all RDS module client-side components:
    Install-RDSClient -R
 
    .LINK
    http://www.heavenbay.ru/app/sintez/help/module/rds#installclient
#>



    [CmdletBinding()]
    Param(
        [switch]$Remove
    )

    $win = $ENV:SYSTEMROOT
    $winjs = $win -replace "\\","\\"
    $RegPath = "HKLM:\SOFTWARE\Classes\rdsmc"
    $ErrorActionPreference = "stop"

    if ($Remove -eq $true) {

        Try {
            Remove-Item -Path $RegPath -Force -Recurse
        }
        Catch [System.Security.SecurityException] {
            Write-Host "Please, start new powershell session with local administrator rights and execute the cmdlet again." -BackgroundColor Black -ForegroundColor Red
            Write-Host ""
            Break
        }
        Catch [System.Management.Automation.ItemNotFoundException] {
            Write-Host "Registry: no item. Skipped..." -BackgroundColor Black -ForegroundColor Yellow
        }

        Try {
            Remove-Item -Path "$win\SnitezRDSMC.js" -Force
        }
        Catch [System.Management.Automation.ItemNotFoundException] {
            Write-Host "JS file: no item. Skipped..." -BackgroundColor Black -ForegroundColor Yellow
        }

        Write-Host ""
        Write-Host "Complited" -BackgroundColor Black -ForegroundColor Green
        Write-Host ""
        break
    }

    Try {
        New-Item -Path $RegPath -Value "URL:Remote Desktop Connection Management Console" -Force | Out-Null
    }
    Catch [System.Security.SecurityException] {
        Write-Host "Please, start new powershell session with local administrator rights and execute the cmdlet again." -BackgroundColor Black -ForegroundColor Red
        Write-Host ""
        Break
    }

    New-ItemProperty -Path $RegPath -Name "URL Protocol" -Force | Out-Null
    New-Item -Path "$RegPath\DefaultIcon" -Value "$win\System32\mstsc.exe" -Force | Out-Null
    New-Item -Path "$RegPath\shell\open\command" -Value "wscript.exe $win\SnitezRDSMC.js %1" -Force | Out-Null
    
    [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("
        dmFyIHN0ckFyZ3M9KFdTY3JpcHQuQXJndW1lbnRzKDApKQp2YXIgcHJlZml4PSdyZHNtYzovLycKc3RyQXJncz1zdHJBcmdzLnJlcGxhY2UocHJlZml4LCAn
        JykKc3RyQXJncz1zdHJBcmdzLnNwbGl0KCcvJykKdmFyIHNoZWxsID0gbmV3IEFjdGl2ZVhPYmplY3QoIldTY3JpcHQuU2hlbGwiKQppZiAoc3RyQXJnc1sw
        XSA9PSAic2hhZG93IikgewogICAgdmFyIGFwcD0nJVdJTkRJUiVcXHN5c3RlbTMyXFxtc3RzYy5leGUnCiAgICBzaGVsbC5FeGVjKGFwcCArICIgL3Y6IiAr
        IHN0ckFyZ3NbMV0gKyAiIC9zaGFkb3c6IiArIHN0ckFyZ3NbMl0gKyAiIC9jb250cm9sIC9ub2NvbnNlbnRwcm9tcHQiKQp9IGVsc2UgaWYgKHN0ckFyZ3Nb
        MF0gPT0gIm1zcmEiKSB7CiAgICB2YXIgYXBwPSclV0lORElSJVxcc3lzV09XNjRcXG1zcmEuZXhlJzsKICAgIHNoZWxsLkV4ZWMoYXBwICsgIiAvb2ZmZXJS
        QSAiICsgc3RyQXJnc1sxXSkKfSBlbHNlIGlmIChzdHJBcmdzWzBdID09ICJSRFAiKSB7CiAgICB2YXIgYXBwPSclV0lORElSJVxcc3lzdGVtMzJcXG1zdHNj
        LmV4ZSc7CiAgICBzaGVsbC5FeGVjKGFwcCArICIgL3Y6IiArIHN0ckFyZ3NbMV0pCn0gZWxzZSB7CiAgICBhbGVydCgnU29tZXRoaW5nIGdvZXMgd3Jvbmch
        Jyk7Cn0K
    "
)) | Out-File -FilePath "$win\SnitezRDSMC.js" -Force 

    Write-Host ""
    Write-Host "Complited!" -BackgroundColor Black -ForegroundColor Green
    Write-Host ""
}

function Start-RDSConnect {


<#
    .SYNOPSIS
    Start-RDSConnect [[-Broker] <String[]>] [-Credential]
 
    .DESCRIPTION
    Gets user list, starts RDP connection (shadow).
  
    .PARAMETER Broker
    -Broker [-B] - RDCB FQDN. Ex.: RDCB1.domain.com.
 
    .PARAMETER Credential
    -Credential [-C] - Credentials switch. Enforce credential form.
 
    .EXAMPLE
    # Start console:
    Start-RDSConnect -B RDCB1.domain.com
 
    .EXAMPLE
    # Start console with credentials prompt:
    Start-RDSConnect -Broker RDCB1.domain.com -C
 
    .LINK
    http://www.heavenbay.ru/app/sintez/help/module/rds#connect
#>



    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)]
        [alias("B")]
        [string]$Broker,
    
        [alias("C")]
        [switch]$Credential

    )

    if ($Credential -eq $true) {
        [PSCredential]$Credential = Get-Credential
    } else {
        [PSCredential]$Credential = [System.Management.Automation.PSCredential]::Empty
    }

    $newCol = SelectCollections $Credential $Broker

    function SessionAction {
        Param (
            [parameter(ValueFromPipelineByPropertyName)]
            [int[]]$SID,

            [parameter(ValueFromPipelineByPropertyName)]
            [string[]]$UserName,

            [parameter(ValueFromPipelineByPropertyName)]
            [string[]]$Host
        )

        Begin {
            $Sessions = @()
        }
        Process {
            $Sessions += "$UserName;$SID;$Host"
        }
        End {
            If ($Sessions.Count -le 0) {
                Write-Host ""
                Write-Host "No sessions. Do nothing."
                Write-Host ""
            }
            ElseIf ($Sessions.Count -eq 1) {
                start-process rdsmc://shadow/$Host/$SID
            }
            Else {
                Write-Host "It's a bad idea to start 100500 RDP sessions. I limit them to 2." -BackgroundColor Black -ForegroundColor Yellow
                Write-Host ""

                foreach($S in $Sessions[0..1]) {
                    [int]$SID = $S.Split(";")[1]
                    [string]$Host = $S.Split(";")[2]
                    start-process rdsmc://shadow/$Host/$SID
                }
            }
        }
    }

    CreateUsersList $Credential $Broker $newCol
}

function Stop-RDSSession {


<#
    .SYNOPSIS
    Stop-RDSSession [[-Broker] <String[]>] [-Credential] [-Force]
 
    .DESCRIPTION
    Initiate user session logoff or reset.
  
    .PARAMETER Broker
    -Broker [-B] - RDCB FQDN. Ex.: RDCB1.domain.com.
 
    .PARAMETER Credential
    -Credential [-C] - Credentials switch. Enforce credential form.
 
    .PARAMETER Force
    -Force [-F] - Force logoff (reset session). Use this option only if logoff does not work. It can corrupt user profile.
 
    .EXAMPLE
    # Starts console, initiates logoff:
    Stop-RDSSession -B RDCB1.domain.com
 
    .EXAMPLE
    # Starts console with credentials prompt, initiates session reset:
    Stop-RDSSession -Broker RDCB1.domain.com -C -F
 
    .LINK
    http://www.heavenbay.ru/app/sintez/help/module/rds#logoff
#>



    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)]
        [alias("B")]
        [string]$Broker,
    
        [alias("C")]
        [switch]$Credential,

        [alias("F")]
        [switch]$Force

    )

    if ($Credential -eq $true) {
        [PSCredential]$Credential = Get-Credential
    } else {
        [PSCredential]$Credential = [System.Management.Automation.PSCredential]::Empty
    }

    If ($Force -eq $true) {
        $cmd = "rwinsta"
    } else {
        $cmd = "logoff"
    }

    $newCol = SelectCollections $Credential $Broker

    function SessionAction {
        Param (
            [parameter(ValueFromPipelineByPropertyName)]
            [int[]]$SID,

            [parameter(ValueFromPipelineByPropertyName)]
            [string[]]$UserName,

            [parameter(ValueFromPipelineByPropertyName)]
            [string[]]$Host
        )

        Begin {
            $Sessions = @()
        }
        Process {
            $Sessions += "$UserName;$SID;$Host"
        }
        End {
            If ($Sessions.Count -le 0) {
                Write-Host ""
                Write-Host "No sessions. Do nothing."
                Write-Host ""
            }
            ElseIf ($Sessions.Count -eq 1) {
                start-process $cmd "$SID /SERVER:$Host" -WindowStyle Hidden
            }
            Else {
                foreach($S in $Sessions) {
                    [int]$SID = $S.Split(";")[1]
                    [string]$Host = $S.Split(";")[2]
                    start-process $cmd "$SID /SERVER:$Host" -WindowStyle Hidden
                }
            }
        }
    }

    CreateUsersList $Credential $Broker $newCol
}

function Set-RDSDrainMode {


<#
    .SYNOPSIS
    Set-RDSDrainMode [[-Broker] <String[]>] [-Credential] [-Enable] [-Disable] [-Reboot]
 
    .DESCRIPTION
    Gets and sets drain mode of RDSH servers. You MUST choose ONE of [-E | -D | -R].
  
    .PARAMETER Broker
    -Broker [-B] - RDCB FQDN. Ex.: RDCB1.domain.com.
 
    .PARAMETER Credential
    -Credential [-C] - Credentials switch. Enforce credential form.
 
    .PARAMETER Enable
    -Enable [-E] - Enable permament drain mode: allow incoming reconnections but prohibit new connections.
 
    .PARAMETER Disable
    -Disable [-D] - Disable drain mode: allow all connections.
 
    .PARAMETER Reboot
    -Reboot [-R] - Enable drain mode until reboot: allow incoming reconnections but until reboot prohibit new connections.
 
    .EXAMPLE
    # Enable drain mode for selected servers:
    Set-RDSDrainMode -B RDCB1.domain.com -E
 
    .LINK
    http://www.heavenbay.ru/app/sintez/help/module/rds#drainmode
#>



    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)]
        [alias("B")]
        [string]$Broker,
    
        [alias("C")]
        [switch]$Credential,

        [parameter(ParameterSetName = "Enable")]
        [alias("E")]
        [switch]$Enable,

        [parameter(ParameterSetName = "Disable")]
        [alias("D")]
        [switch]$Disable,

        [parameter(ParameterSetName = "Reboot")]
        [alias("R")]
        [switch]$Reboot

    )

    if ($Credential -eq $true) {
        [PSCredential]$Credential = Get-Credential
    } else {
        [PSCredential]$Credential = [System.Management.Automation.PSCredential]::Empty
    }

    $newCol = SelectCollections $Credential $Broker

    function getDrainMode([int]$DrainModeId) {
        [string]$rez = "###";
        switch ($DrainModeId) {
            0 {$rez = "OFF"}
            2 {$rez = "ON"}
            1 {$rez = "ON, REBOOT"}
            default {$rez = "Something goes wrong."}
        }
        return $rez
    }

    if ($Disable) {
        [int]$DSwitch = "0"
    }
    ElseIf ($Enable) {
        [int]$DSwitch = "2"
    }
    ElseIf ($Reboot) {
        [int]$DSwitch = "1"
    }
    ElseIf (!($Disable -or $Enable -or $Reboot)) {
        Write-Host "Nothing selected. Choose one:"
        Write-Host "Set-RDSDrainMode -B BROKER -E"
        Write-Host "Set-RDSDrainMode -B BROKER -D"
        Write-Host "Set-RDSDrainMode -B BROKER -R"
        Break
    }

    function SessionAction {
        Param (
            [parameter(ValueFromPipelineByPropertyName)]
            [string[]]$Host,

            [parameter(ValueFromPipelineByPropertyName)]
            [string[]]$DrainMode

        )

        Begin {
            $Hosts = @()
        }
        Process {
            $Hosts += "$DrainMode;$Host"
        }
        End {
            If ($Hosts.Count -le 0) {
                Write-Host ""
                Write-Host "No sessions. Do nothing."
                Write-Host ""
            }
            ElseIf ($Hosts.Count -eq 1) {
                try {
                    Set-WmiInstance -Credential $Credential -Class "Win32_TerminalServiceSetting" -Namespace "root\CIMV2\terminalservices" -Arguments @{SessionBrokerDrainMode=$DSwitch} -ComputerName $Host | Out-Null
                }
                Catch [System.Runtime.InteropServices.COMException] {
                    Write-Host "Unable to connect to server: $Host. Skip it." -BackgroundColor Black -ForegroundColor Red
                }
            }
            Else {
                foreach($H in $Hosts) {
                    [string]$DrainMode = $H.Split(";")[0]
                    [string]$Host = $H.Split(";")[1]
                    try {
                        Set-WmiInstance -Credential $Credential -Class "Win32_TerminalServiceSetting" -Namespace "root\CIMV2\terminalservices" -Arguments @{SessionBrokerDrainMode=$DSwitch} -ComputerName $Host | Out-Null
                    }
                    Catch [System.Runtime.InteropServices.COMException] {
                        Write-Host "Unable to connect to server: $Host. Skip it." -BackgroundColor Black -ForegroundColor Red
                    }
                }
            }
        }
    }

    $($newCol.Keys) | %{
        $RDSH = $_; 
        Get-WmiObject -Credential $Credential -Class "Win32_TerminalServiceSetting" -Namespace "root\CIMV2\terminalservices" -ComputerName $RDSH `
        | select `
        @{Label="Host";Expression={$RDSH}}, `
        @{Label="Collection";Expression={$newCol[$RDSH]}}, `
        @{Label="DrainMode";Expression={getDrainMode($_.SessionBrokerDrainMode)}}} `
        | Sort "Host" `
        | Out-GridView -PassThru -Title "RDSH Drain Mode Status" `
        | SessionAction
}

function Send-RDSPrivateMessage {


<#
    .SYNOPSIS
    Send-RDSPrivateMessage [[-Broker] <String[]>] [[-Message] <String[]>] [-Credential]
 
    .DESCRIPTION
    Sends private message to users.
  
    .PARAMETER Broker
    -Broker [-B] - RDCB FQDN. Ex.: RDCB1.domain.com.
 
    .PARAMETER Message
    -Message [-M] - Message text.
 
    .PARAMETER Credential
    -Credential [-C] - Credentials switch. Enforce credential form.
 
    .EXAMPLE
    # Send private message to selected users:
    Send-RDSPrivateMessage -B rdcb.domain.com -M "Hey! Big bro is watching you :)"
 
    .LINK
    http://www.heavenbay.ru/app/sintez/help/module/rds#pmessage
#>



    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)]
        [alias("B")]
        [string]$Broker,
    
        [Parameter(Mandatory=$true)]
        [alias("M")]
        [string]$Message,

        [alias("C")]
        [switch]$Credential
    )

    if ($Credential -eq $true) {
        [PSCredential]$Credential = Get-Credential
    } else {
        [PSCredential]$Credential = [System.Management.Automation.PSCredential]::Empty
    }

    $newCol = SelectCollections $Credential $Broker

    function SessionAction {
        Param (
            [parameter(ValueFromPipelineByPropertyName)]
            [int[]]$SID,

            [parameter(ValueFromPipelineByPropertyName)]
            [string[]]$UserName,

            [parameter(ValueFromPipelineByPropertyName)]
            [string[]]$Host
        )

        Begin {
            $Sessions = @()
        }
        Process {
            $Sessions += "$UserName;$SID;$Host"
        }
        End {
            If ($Sessions.Count -le 0) {
                Write-Host ""
                Write-Host "No sessions. Do nothing."
                Write-Host ""
            }
            ElseIf ($Sessions.Count -eq 1) {
                start-process msg "$SID /SERVER:$Host /TIME:180 $Message" -WindowStyle Hidden
            }
            Else {
                foreach($S in $Sessions) {
                    [int]$SID = $S.Split(";")[1]
                    [string]$Host = $S.Split(";")[2]
                    start-process msg "$SID /SERVER:$Host /TIME:180 $Message" -WindowStyle Hidden
                }
            }
        }
    }

    CreateUsersList $Credential $Broker $newCol

}

function Send-RDSMassiveMessage {


<#
    .SYNOPSIS
    Send-RDSMassiveMessage [[-Broker] <String[]>] [[-Message] <String[]>] [-Credential]
 
    .DESCRIPTION
    Sends massive message to ALL users on server.
  
    .PARAMETER Broker
    -Broker [-B] - RDCB FQDN. Ex.: RDCB1.domain.com.
 
    .PARAMETER Message
    -Message [-M] - Message text.
 
    .PARAMETER Credential
    -Credential [-C] - Credentials switch. Enforce credential form.
 
    .EXAMPLE
    # Send massive message to ALL users on selected servers:
    Send-RDSMassiveMessage -B rdcb.domain.com -M "Hey! Big bro is watching you :)"
 
    .LINK
    http://www.heavenbay.ru/app/sintez/help/module/rds#mmessage
#>



    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true)]
        [alias("B")]
        [string]$Broker,
    
        [Parameter(Mandatory=$true)]
        [alias("M")]
        [string]$Message,

        [alias("C")]
        [switch]$Credential
    )

    if ($Credential -eq $true) {
        [PSCredential]$Credential = Get-Credential
    } else {
        [PSCredential]$Credential = [System.Management.Automation.PSCredential]::Empty
    }

    $newCol = SelectCollections $Credential $Broker

    function SessionAction {
        Param (
            [parameter(ValueFromPipelineByPropertyName)]
            [string[]]$Host
        )

        Begin {
            $arHost = @()
        }
        Process {
            $arHost += "$Host"
        }
        End {
            If ($arHost.Count -le 0) {
                Write-Host ""
                Write-Host "No sessions. Do nothing."
                Write-Host ""
            }
            ElseIf ($arHost.Count -eq 1) {
                start-process msg "* /SERVER:$Host /TIME:180 $Message" -WindowStyle Hidden
            }
            Else {
                foreach($Host in $arHost) {
                    start-process msg "* /SERVER:$Host /TIME:180 $Message" -WindowStyle Hidden
                }
            }
        }
    }

    gwmi -ComputerName $Broker -Credential $Credential -Query "SELECT ServerName,NumberOfSessions FROM Win32_SessionDirectoryServer" `
    | select `
    @{Label="Host";Expression={$_.ServerName}},`
    @{Label="Collections";Expression={$newCol[$_.ServerName]}},`
    @{Label="Sessions";Expression={$_.NumberOfSessions}} `
    | sort Host `
    | Out-GridView -PassThru -Title "Massive Message - Select Servers" `
    | SessionAction

}

Export-ModuleMember -Function "Install-RDSServer", "Install-RDSClient", "Start-RDSConnect","Stop-RDSSession","Set-RDSDrainMode","Send-RDSPrivateMessage","Send-RDSMassiveMessage"