| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626 | 
							- <#
 
- .DESCRIPTION
 
- Ñêðèïò ìèãðàöèè ïðàâèë ñåòåâîãî ýêðàíà Trust Access â Secret Net Studio. Çàïóñêàåòñÿ ïîä ïîëüçîâàòåëåì èìåþùèì ïðàâà àäìèíèñòðàòîðà íà ñåðâåðå áåçîïàñíîñòè SNS. Äëÿ ðàáîòû ñêðèïòà íåîáõîäèìî, ÷òîáû íà äîìåí êîíòðîëëåðå è ñåðâåðå áåçîïàñíîñòè Secret Net Studio áûëà äîñòóïíà ñëæáà WinRM.
 
- .PARAMETER AuthXMLpath
 
- Ïóòü ê ôàéëó ñ êîíôèãóðàöèåé Auth.xml èç TrustAccess.
 
- .PARAMETER SSSNSName
 
- Èìÿ èëè IP àäðåññ ñåðâåðà áåçîïàñíîñòè SNS êóäà èìïîðòèðóþòñÿ ïðàâèëà.
 
- .PARAMETER GroupMappingFile
 
- Ïóòü ê TXT ôàéëó â êîòîðîì ïåðå÷èñëåííî ñîîòâåòñòâèå ãðóïï TrustAccess ãðóïïàì â AD.
 
- Ïðèìåð:
 
- Taadmins,SNSadmins
 
- TAUsers,SNSlUsers
 
- TAVIP,SNSHUsers
 
- User TrustAccess,SNS Users S
 
- .PARAMETER DC
 
- Èìÿ èëè IP àäðåññ äîìåí êîíòðîëëåðà èñïîëüçóåòñÿ äëÿ ïîèñêà ãðóïï TrustAccess â AD è ïåðåìåùåíèÿ èõ â SNS.
 
- .PARAMETER FallBackGroup
 
- Èìÿ ãðóïïû êîòîðàÿ èñïîëüçóåòñÿ äëÿ çàäàíèÿ â ïðàâèëàõ ó êîòîðûõ íå óäàëîñü íàéòè ñîîòâåòñòâèå ãðóïïû â TrustAccess ãðóïïå â AD.
 
- .PARAMETER RunAs
 
- Ïàðàìåòð ïåðåäàâàåìûé åñëè äëÿ äîñòóïà ê AD è äîñòóïó ê Ñåðâåðó Áåçîïàñíîñòè SNS òðåáóåòñÿ èñïîëüçîâàòü ó÷åòíóþ çàïèñü ïîëüçîâàòåëÿ îòëè÷íóþ îò òåêóùåãî.
 
- .PARAMETER OnlyCurrentComputer
 
- Èñïîëüçóåòñÿ äëÿ àâòîíîìíîé âåðñèè Secret Net Studio, èç ôàéëà êîíôèãóðàöèè TrustAccess çàãðóæàþòñÿ òîëüêî ïðàâèëà äëÿ ýòîãî êîìïüþòåðà.
 
- .PARAMETER EnableProtectionEveryone
 
- Ïàðàìåòð äëÿ çàäàíèÿ ïîëèòèêè "Çàùèòà ñîåäèíåíèé äëÿ ãðóïïû everyone" äëÿ âñåõ àãåíòîâ.
 
- .PARAMETER OnlyViewRule
 
- Èñïîëüçóåòñÿ äëÿ òåñòâîãî çàïóñêà ñêðèïòà, èìïîðòèðîâàííûå ïðàâèëà íå çàãðóçàþòñÿ íà ñåðâåð áåçîïàñíîñòè, à òîëüêî âûâîäÿòñÿ íà ýêðàí.
 
- .EXAMPLE 
 
- Move-RuleFromTAtoAS.ps1 -AuthXMLpath D:\AuthWithUser.xml -SSSNSName lse2016-3.some.local -DC PDC.SOME.LOCAL -FallBackGroup snsadmins -RunAs -OnlyViewRule -GroupMappingFile D:\grouplist.txt
 
-  ýòîì ïðèìåðå ñêðèïò çàïóñêàåòñÿ íà ÑÁ lse2016-3.some.local, ãðóïïà ïî-óìîë÷àíèþ snsadmins,  äëÿ ãðóïï Òrust Access êîòîðûì íå óäàëîñü íàéòè ñîîòâåòñòâèå â ôàéëå ñîîòâåòñòâèÿ èëè Active Directory. Ïðàâèëà áóäóò âûâåäåíû íà ýêðàí, íî íå áóäóò çàãðóæåíû íà ñåðâåð. 
 
- .EXAMPLE 
 
- Move-RuleFromTAtoAS.ps1 -AuthXMLpath D:\AuthWithUser.xml -SSSNSName lse2016-3.some.local -OnlyViewRule -GroupMappingFile D:\grouplist.txt
 
- Â ýòîì ïðèìåðå ñêðèïò çàïóñêàåòñÿ íà ÑÁ lse2016-3.some.local, óêàçàí ôàéë ñîîòâåòñòâèÿ ãðóïï Trust Access ãðóïïàì â Active Directory. Ïðàâèëà áóäóò âûâåäåíû íà ýêðàí, íî íå áóäóò çàãðóæåíû íà ñåðâåð. 
 
- .EXAMPLE
 
- Move-RuleFromTAtoAS.ps1 -AuthXMLpath D:\AuthWithUser.xml -RunAs -OnlyViewRule -OnlyCurrentComputer
 
- Ñêðèïò çàïóñêàåòñÿ ëîêàëüíî íà àãåíòå SNS (ëîêàëüíàÿ âåðñèÿ), áóäóò èìïîðòèðîâàíû ïðàâèëà äëÿ ýòîãî àãåíòà. Â ëîêàëüíîì ðåæèìå èãíîðèðóþòñÿ ãðóïïû è âñå ïðâèëà ïîñëå èìïîðòà áóäóò ñîîñòâåòñòâîâàòü ãðóïïå everyone.
 
- #>
 
- #Requires -Version 2
 
- [CmdletBinding(DefaultParameterSetName = 'Remote')]
 
- Param(
 
-     [Parameter(Mandatory = $True, ParameterSetName = 'Local')]
 
-     [Parameter(Mandatory = $True, ParameterSetName='Remote')]
 
-     [ValidateScript( {(Test-Path -Path $_ -Type Leaf)} )]
 
-     [String]$AuthXMLpath,
 
-     [Parameter(Mandatory = $false, ParameterSetName = 'Remote')]
 
-     [String] $SSSNSName = $env:COMPUTERNAME,
 
-     [Parameter(Mandatory = $false, ParameterSetName = 'Local')] 
 
-     [Parameter(Mandatory = $false, ParameterSetName='Remote')]
 
-     [ValidateScript( {(Test-Path -Path $_ -Type Leaf)} )]
 
-     [String] $GroupMappingFile,
 
-     [Parameter(Mandatory = $false, ParameterSetName = 'Local')]
 
-     [Parameter(Mandatory = $false, ParameterSetName='Remote')]
 
-     [String] $DC = ('{0}.{1}' -f (($env:LOGONSERVER).replace('\\','')), $env:USERDNSDOMAIN),
 
-     [Parameter(Mandatory = $false, ParameterSetName='Remote')]
 
-     [String] $FallBackGroup = "Everyone",
 
-     [Parameter(Mandatory = $false, ParameterSetName = 'Local')]
 
-     [Parameter(Mandatory = $false, ParameterSetName='Remote')]
 
-     [Switch] $RunAs = $false,
 
-     [Parameter(Mandatory = $true, ParameterSetName = 'Local')]
 
-     [Switch] $OnlyCurrentComputer = $false,
 
-     [Parameter(Mandatory = $false, ParameterSetName = 'Local')]
 
-     [Parameter(Mandatory = $false, ParameterSetName='Remote')]
 
-     [Switch] $EnableProtectionEveryone = $false,
 
-     [Parameter(Mandatory = $false, ParameterSetName = 'Local')]
 
-     [Parameter(Mandatory = $false, ParameterSetName='Remote')]
 
-     [Switch] $OnlyViewRule = $false
 
- )
 
- BEGIN {
 
-     Set-StrictMode -Version 2.0 
 
-     $ErrorActionPreference = 'Stop'
 
-     [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Management.Automation")
 
-     #### V A R I A B L E #### 
 
-     ##### SCRIPT #####
 
-     New-Variable -Name CREDENTIALS -Scope Script -Value $null -Force
 
-     New-Variable -Name SSSESSION -Scope Script -Value $null -Force
 
-     New-Variable -Name DCSESSION -Scope Script -Value $null -Force 
 
-     New-Variable -Name GROUPMAPPING -Scope Script -Value (New-Object System.Collections.Hashtable) -Force
 
-     New-Variable -Name AUTHXML -Scope Script -Value (New-Object System.Collections.Hashtable) -Force
 
-     ##### SCRIPT #####
 
-     $LogsPath                           = 'C:\Logs'
 
-     $LogFile                            = (Join-Path -Path $LogsPath -ChildPath 'Move-RuleFromTAtoAS.log')
 
-     $NGFWREGPATH                        = "HKLM:\SOFTWARE\Security Code\Secret Net Studio\Client\Network Protection"
 
-     $AUTHSRVREGPATH                        = "HKLM:\SOFTWARE\Security Code\Secret Net Studio\Server\Authentication Server"
 
-     $ORDERRAGE                          = @{
 
-         'network-transport-rules'       = 101000
 
-         'network-layer-rules'           = 100000
 
-         'network-transport-with-auth-rules' = 110000
 
-         'pipe-rules'                    = 121000
 
-         'smb-folder-rules'              = 120000
 
-     }
 
-     $GROUPSNAME                         = @{
 
-         '{00000001-0000-0000-0000-000000000000}'    =   'Everyone'
 
-         '{00000002-0000-0000-0000-000000000000}'    =   'Anonymous'
 
-         '{00000003-0000-0000-0000-000000000000}'    =   'Authenticated'
 
-         '{00000004-0000-0000-0000-000000000000}'    =   'Computers'
 
-         '{00000005-0000-0000-0000-000000000000}'    =   'Users'
 
-     }
 
-  
 
-     [String]$ScSrvConfig                = $null
 
-     [String[]]$ScSrvConfigArg           = $null
 
-     $AUTHMODCFGPATH                     = '\auth-mod-cfg\'
 
-     $SERVERSPATH                        = (Join-Path -Path $AUTHMODCFGPATH -ChildPath '\servers\')
 
-     $AGENTSPATH                         = (Join-Path -Path $AUTHMODCFGPATH -ChildPath '\agents\')
 
-     $GROUPSPATH                         = '\groups\'
 
-     $USERSPATH                          = '\users\'
 
-     $SYSGROUPSPATH                      = '\system_groups\'
 
-     $Everyone                           = 'Everyone'
 
-     $ACCESSRULESPATH                    = (Join-Path -Path $AuthModCfgPath -ChildPath '\accessrules\')
 
-     $ALLPRINCIPAL                       = 'principal'
 
-     $PSMODULES                          = @('ActiveDirectory')
 
-     $CRYPTOFNNAME                       = @('Get-PassFromCredential', 'ConvertTo-CredentialsAsEncryptedStringWinthPSK', 'ConvertFrom-CredentialsAsEncryptedStringWinthPSK', 'Get-CredentialBySecretString')
 
-     $PSK                                = (-join ((65..90) + (97..122) | Get-Random -Count 5 | ForEach-Object {[char]$_}) )  # Ïðåäâàðèòåëüíûé îáùèé êëþ÷, èñïîëüçóåòñÿ äëÿ îáìåíà ïàðîëåì ïîëüçîâàòåëÿ.
 
-     $COMMONFN                           = @('Trace-Message', 'Trace-VerboseMessage', 'Trace-ErrorMessage')
 
-     $RemoteGlobalVar                    = @{
 
-         LogFile                         = $LogFile
 
-         NGFWREGPATH                     = $NGFWREGPATH
 
-         AUTHSRVREGPATH                  = $AUTHSRVREGPATH
 
-     }
 
-     try {[NGFRRule]} catch [Management.Automation.RuntimeException] {
 
-         $code = @"
 
-         using System;
 
-         using System.Collections;
 
-         using System.Collections.Generic;
 
-         public enum ON_OFF_STATUS : int {
 
-             OFF = 0,
 
-             ON = 1
 
-         }
 
-         public static class ProtocolType {
 
-             private static readonly Dictionary<string, string> PotocolNameDict = new Dictionary<string, string>();
 
-             static ProtocolType (){
 
-                 PotocolNameDict.Add( "1", "ICMP" );
 
-                 PotocolNameDict.Add( "2", "IGMP" );
 
-                 PotocolNameDict.Add( "6", "TCP" );
 
-                 PotocolNameDict.Add( "8", "EGP" );
 
-                 PotocolNameDict.Add( "17", "UDP" );
 
-                 PotocolNameDict.Add( "20", "HMP" );
 
-                 PotocolNameDict.Add( "22", "XNS" );
 
-                 PotocolNameDict.Add( "27", "RDP" );
 
-                 PotocolNameDict.Add( "66", "RVD" );
 
-                 PotocolNameDict.Add( "*", "ALL" );
 
-             }
 
-             
 
-             public static string GetProtocolType(string propname){
 
-                 string result;
 
-                 if (PotocolNameDict.TryGetValue(propname, out result))
 
-                 {
 
-                     return result;
 
-                 }
 
-                 else
 
-                 {
 
-                     return null;
 
-                 }
 
-             }
 
-         }
 
-         public static class SmbService {
 
-             private static readonly Dictionary<string, string> ServicesNameDict = new Dictionary<string, string>();
 
-             static SmbService () {
 
-                 ServicesNameDict.Add( "smb-folder", "Shared folders" );
 
-                 ServicesNameDict.Add( "pipes", "Named pipes" );
 
-             }
 
-             public static string GetService(string propname){
 
-                 string result;
 
-                 if (ServicesNameDict.TryGetValue(propname, out result))
 
-                 {
 
-                     return result;
 
-                 }
 
-                 else
 
-                 {
 
-                     return null;
 
-                 }
 
-             } 
 
-         }
 
-         public static class GroupsName {
 
-             private static readonly Dictionary<string, string> ServicesNameDict = new Dictionary<string, string>();
 
-             static GroupsName() {
 
-                 ServicesNameDict.Add( "{00000001-0000-0000-0000-000000000000}", "Everyone" );
 
-                 ServicesNameDict.Add( "{00000002-0000-0000-0000-000000000000}", "Anonymous" );
 
-                 ServicesNameDict.Add( "{00000003-0000-0000-0000-000000000000}", "Authenticated" );
 
-                 ServicesNameDict.Add( "{00000004-0000-0000-0000-000000000000}", "Computers" );
 
-                 ServicesNameDict.Add( "{00000005-0000-0000-0000-000000000000}", "Users" );
 
-             }
 
-             public static string GetGroup(string propname){
 
-                 string result;
 
-                 if (ServicesNameDict.TryGetValue(propname, out result))
 
-                 {
 
-                     return result;
 
-                 }
 
-                 else
 
-                 {
 
-                     return null;
 
-                 }
 
-             }
 
-         }
 
-         public class NGFWRule {
 
-             public NGFWRule (Hashtable rule){
 
-                 this.Status = (ON_OFF_STATUS)Enum.Parse(typeof(ON_OFF_STATUS), (string)(rule["enabled"]));
 
-                 this.Audit = (ON_OFF_STATUS)Enum.Parse(typeof(ON_OFF_STATUS), (string)rule["audit-enabled"]);
 
-                 this.Accesstype = (string)rule["accesstype"];
 
-                 this.Remoteaddress = (string)rule["remote-addrs"];
 
-             }
 
-             private ON_OFF_STATUS _Status;
 
-             public ON_OFF_STATUS Status{ get{return _Status;} set {_Status = value;}}
 
-             private ON_OFF_STATUS _Audit;
 
-             public ON_OFF_STATUS Audit {get{return _Audit;} set {_Audit = value;}}
 
-             private string _Accesstype;
 
-             public string Accesstype {get{return _Accesstype;} set {_Accesstype = value;}}
 
-             private string _Remoteaddress;
 
-             public string Remoteaddress {get{return _Remoteaddress;} set {_Remoteaddress = value;}}
 
-         }
 
-         public class NGFWNetworkTransportRule : NGFWRule {
 
-             public NGFWNetworkTransportRule (Hashtable rule) : base(rule){
 
-                 this.Protocol = ProtocolType.GetProtocolType((string)rule["protocol"]);
 
-             }
 
-             private string _Protocol;
 
-             public string Protocol {get{return _Protocol;} set {_Protocol = value;}}
 
-         }
 
-         public class NGFWPipeRule : NGFWRule {
 
-             public NGFWPipeRule (Hashtable rule) : base(rule){
 
-                 this.Subject = GroupsName.GetGroup((string)rule["groups"]) + (string)rule["external-subjects"];
 
-                 this.service = SmbService.GetService((string)rule["service"]);
 
-                 this.accessobject = (string)rule["pipe-name"];
 
-             }
 
-             private string _Subject;
 
-             public string Subject {get{return _Subject;} set {_Subject = value;}}
 
-             private string _service;
 
-             public string service {get{return _service;} set {_service = value;}}
 
-             private string _accessobject;
 
-             public string accessobject {get{return _accessobject;} set {_accessobject = value;}}
 
-         }
 
-         public class NGFWSMBRule : NGFWRule {
 
-             public NGFWSMBRule (Hashtable rule) : base(rule){
 
-                 string resSubj = GroupsName.GetGroup((string)rule["groups"]) + (string)rule["external-subjects"];
 
-                 this.Subject = resSubj;
 
-                 this.service = SmbService.GetService((string)rule["service"]);
 
-                 this.accessobject = (string)rule["folder-path-mask"];
 
-             }
 
-             private string _Subject;
 
-             public string Subject {get{return _Subject;} set {_Subject = value;}}
 
-             private string _service;
 
-             public string service {get{return _service;} set {_service = value;}}
 
-             private string _accessobject;
 
-             public string accessobject {get{return _accessobject;} set {_accessobject = value;}}
 
-         }
 
-         public class NGFWNetworkWithAuthRule : NGFWRule {
 
-             public NGFWNetworkWithAuthRule (Hashtable rule) : base(rule){
 
-                 this.Direction = (string)rule["rule-direction-type"];
 
-                 this.Protocol = ProtocolType.GetProtocolType((string)rule["protocol"]);
 
-                 this.Subject = GroupsName.GetGroup((string)rule["groups"]) + (string)rule["external-subjects"];
 
-                 this.Remoteports = (string)rule["remote-ports"];
 
-                 this.Localaddress = (string)rule["local-addrs"];
 
-                 this.Localports = (string)rule["local-ports"];
 
-                 this.Application = (string)rule["processes-to-include"];
 
-             }
 
-             private string _Direction;
 
-             public string Direction {get{return _Direction;} set {_Direction = value;}}
 
-             private string _Protocol;
 
-             public string Protocol {get{return _Protocol;} set {_Protocol = value;}}
 
-             private string _Subject;
 
-             public string Subject {get{return _Subject;} set {_Subject = value;}}
 
-             private string _Remoteports;
 
-             public string Remoteports {get{return _Remoteports;} set {_Remoteports = value;}}
 
-             private string _Localaddress;
 
-             public string Localaddress {get{return _Localaddress;} set {_Localaddress = value;}}
 
-             private string _Localports;
 
-             public string Localports {get{return _Localports;} set {_Localports = value;}}
 
-             private string _Application;
 
-             public string Application {get{return _Application;} set {_Application = value;}}
 
-         }
 
- "@
 
-         Add-Type -TypeDefinition $code -PassThru -WarningAction SilentlyContinue | Out-Null
 
-     }
 
-     #### V A R I A B L E ####
 
-     [String]$DefaultTemplateName = 'Default' 
 
-     if($RunAs){
 
-         $Script:CREDENTIALS = $Host.ui.PromptForCredential("Enter credential", "Please enter your user name and password.", "", "Domain User") 
 
-     } else {
 
-         $Script:CREDENTIALS = $Host.ui.PromptForCredential("Enter credential", "Please enter current user password.", ($([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)), "Domain User")
 
-     }
 
- }
 
- Process {
 
-     Trap {
 
-         $LastErr = $Error[0]
 
-         $Msg =@(
 
-             $LastErr.Exception.Message
 
-             $LastErr.Exception.StackTrace
 
-         )
 
-         Trace-ErrorMessage -Msg $Msg
 
-         Remove-ScriptVariable
 
-         break
 
-     }
 
-     function Trace-Message {
 
-         [CmdletBinding()]
 
-         Param(
 
-             [Parameter(ValueFromPipeline=$true)]
 
-             [String[]]$Msg = ""
 
-         )
 
-         Begin {[String]$FormattedMsg = $null}
 
-         Process  {
 
-             $FormattedMsg = ("{0:yyyy}/{0:MM}/{0:dd}-{0:HH}:{0:mm}:{0:ss}: " -f (Get-Date)) + $Msg
 
-             Write-Verbose -Msg $FormattedMsg
 
-             if ($null -ne $Script:LogFile) {
 
-                 try {
 
-                     $FormattedMsg | Out-File -FilePath $Script:LogFile -Append -Encoding bigendianunicode -Force
 
-                 }
 
-                 Catch [System.IO.DirectoryNotFoundException] {
 
-                     New-Item -Path  (Split-path $Script:LogFile -Parent) -ItemType Directory
 
-                 }
 
-             }
 
-         }
 
-     }
 
-     function Trace-ErrorMessage {
 
-         Param(
 
-             [Parameter(ValueFromPipeline=$true)]
 
-             [String[]]$Msg = ""
 
-             )
 
-             PROCESS {
 
-                 Trace-Message -Msg $Msg
 
-                 Write-Error -Message ([String]$Msg)
 
-             }
 
-     }
 
-     function Trace-VerboseMessage {
 
-         Param(
 
-             [Parameter(ValueFromPipeline=$true)]
 
-             [String[]]$Msg = ""
 
-         )
 
-         PROCESS {
 
-             if( $Script:PSBoundParameters.ContainsKey('Verbose') ){
 
-                 Trace-Message -Msg $Msg
 
-             }
 
-         }
 
-     }
 
-     function Remove-ScriptVariable {
 
-         Remove-Variable -Name CREDENTIALS -Scope Script -ErrorAction SilentlyContinue
 
-         if($Script:SSSESSION){
 
-             Remove-PSSession -Session $Script:SSSESSION -ErrorAction SilentlyContinue
 
-         }
 
-         Remove-Variable -Name SSSESSION -Scope Script -ErrorAction SilentlyContinue
 
-         if($Script:DCSESSION){
 
-             Remove-PSSession -Session $Script:DCSESSION -ErrorAction SilentlyContinue
 
-         }
 
-         Remove-Variable -Name DCSESSION -Scope Script -ErrorAction SilentlyContinue
 
-         Remove-Variable -Name GROUPMAPPING -Scope Script -ErrorAction SilentlyContinue
 
-         Remove-Variable -Name AUTHXML -Scope Script -ErrorAction SilentlyContinue
 
-     }
 
-     function Invoke-FnRemote {
 
-         Param(
 
-             [Parameter(Mandatory=$false)]
 
-             [String[]]$InitializationScript = $null,
 
-             [Parameter(Mandatory=$true)]
 
-             [ValidateNotNullOrEmpty()]
 
-             [String]$FunctionName,
 
-             [Parameter(Mandatory=$true)]
 
-             [ValidateNotNullOrEmpty()]
 
-             [System.Management.Automation.Runspaces.PSSession]$PSsession,
 
-             [Parameter(Mandatory=$false)]
 
-             [Hashtable[]]$ArgList = $null
 
-         )
 
-         Begin {
 
-             $StartBlock = 'Param([Hashtable]$param);.{'
 
-             $sb = $null
 
-         }
 
-         Process {
 
-             if ($null -ne $InitializationScript) {
 
-                 $InitializationScript |ForEach-Object{
 
-                     $ScriptFunctionName = $_
 
-                     Trace-VerboseMessage ('Add function:  {0}' -f $ScriptFunctionName)
 
-                     try {
 
-                         $sb = [scriptblock]::create( "$sb function $ScriptFunctionName{$((Get-Item ('Function:\{0}' -f $ScriptFunctionName)).ScriptBlock)}`r`n")
 
-                     }
 
-                     Catch [Management.Automation.ItemNotFoundException] {
 
-                         Throw ('Could not find an implementation for function: {0}' -f $ScriptFunctionName)
 
-                     }
 
-                     Catch {
 
-                         Throw $_
 
-                     }
 
-                     Trace-VerboseMessage ('Result   {0}' -f $sb)
 
-                 }
 
-                 } else {
 
-                     Trace-VerboseMessage "No InitializationScript" 
 
-                 }
 
-         }
 
-         End {
 
-             $sb = [scriptblock]::create("$StartBlock $sb function $FunctionName{$((Get-Item ('Function:\{0}' -f $FunctionName)).ScriptBlock)} }; $FunctionName @param")
 
-             $res = Invoke-Command -Session $PSsession -ScriptBlock $sb -ArgumentList $ArgList
 
-             return $res
 
-         }
 
-     }
 
-     function ConvertTo-Scriptblock {
 
-         <#
 
-             .SYNOPSIS
 
-             Function to Convert a String into a Script Block
 
-         #>
 
-         Param(
 
-             [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
 
-             [string]$string
 
-         )
 
-         $scriptBlock = [scriptblock]::Create($string)
 
-         return $scriptBlock
 
-     }
 
-     function Get-PassFromCredential {
 
-         <#
 
-             .SYNOPSIS
 
-             Extract user password from credential.
 
-         #>
 
-         Param(
 
-             [Parameter(Mandatory=$True)]
 
-             [System.Management.Automation.PSCredential]$Credential
 
-         )
 
-         $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Credential.Password)
 
-         return [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
 
-     }
 
-     function Invoke-RemoteWithArguments {
 
-         <#
 
-             .SYNOPSIS
 
-             Invoke function on remote server.
 
-         #>
 
-         Param(
 
-             [Parameter(Mandatory=$false)]
 
-             [Hashtable] $Param,
 
-             [Parameter(Mandatory=$true)]
 
-             [String] $InvokeExpression,
 
-             [Parameter(Mandatory=$false)]
 
-             [switch] $Force = $false,
 
-             [Parameter(Mandatory = $false)] [ValidateSet('Global', 'Local', 'Script')]
 
-             [String] $Scope = 'Local'
 
-             )
 
-         if($Param -ne $null) {
 
-             $Param.GetEnumerator() |ForEach-Object{
 
-                 New-Variable -Name $_.Key -Value $_.Value -scope  $Scope -Force:$Force
 
-             }
 
-             if ($Param['PSBoundParameters']){
 
-                 $script:PSBoundParameters = $Param['PSBoundParameters']
 
-             }
 
-         }
 
-         Invoke-Expression $InvokeExpression 
 
-     }
 
-     
 
-     function Invoke-FnRemoteCommonWrapper{
 
-         <#
 
-             .SYNOPSIS
 
-             Wrapper on Invoke-FnRemote function, invoke only functions that meet the requirements verb naming rules Windows Powershell.
 
-         #>
 
-         Param(
 
-             [Parameter(Mandatory=$True)]
 
-             [ValidateNotNullOrEmpty()]
 
-             [System.Management.Automation.Runspaces.PSSession] $PSsession,
 
-             [Parameter(Mandatory=$True)]
 
-             [String] $InvokeExpression,
 
-             [Parameter(Mandatory=$False)]
 
-             [Hashtable] $Parameters = $null,
 
-             [Parameter(Mandatory=$false)]
 
-             [String[]] $AdditionalDependencies,
 
-             [Parameter(Mandatory=$false)]
 
-             [Switch] $Force = $false
 
-         )
 
-         [String]$InvokeFunction = $InvokeExpression |Select-String -Pattern  '(\w+-\w+)(?:\s.+|$)' |ForEach-Object{$_.Matches|ForEach-Object{$_.groups[1].Value}}
 
-         [String[]]$FunctionDep = Get-DependentFunctions -FunctionName $InvokeFunction
 
-         if (-not $InvokeFunction) {throw 'Attempting to call a function whose name does not meet the requirements functions verb naming rules Windows PowerShell.'}
 
-         $res = Invoke-FnRemote -PSSession $PSsession -InitializationScript (@($Script:COMMONFN + $FunctionDep + $AdditionalDependencies + $InvokeFunction)|Select-Object -Unique) -FunctionName 'Invoke-RemoteWithArguments' -ArgList @{
 
-             Param = $Parameters
 
-             InvokeExpression = $InvokeExpression
 
-             Force        = $Force
 
-             Scope        = 'Local'
 
-         } 
 
-         return $res
 
-     }
 
-     function Get-DependentFunctions{
 
-         <#
 
-             .SYNOPSIS
 
-             Returns the dependencies of a function from its description.
 
-         #>
 
-         [OutputType([System.Collections.ArrayList])]
 
-         Param(
 
-             [Parameter(Mandatory=$true)]
 
-             [ValidateNotNullOrEmpty()]
 
-             [String] $functionName
 
-             )
 
-         $fnHelpTemplate = 'RequiredFunction<(?<function>.*?)\>'
 
-         $DependentFunctions = New-Object System.Collections.ArrayList
 
-         try {
 
-             [String[]]$RequiredFunction = (get-help $functionName).alertSet.alert[0].text -split "\n" |Where-Object{$_ -match $fnHelpTemplate }
 
-         }
 
-         Catch {
 
-             Trace-VerboseMessage -Msg 'No function dependency description was found.'
 
-             return $null
 
-         }
 
-         if($RequiredFunction -ne $null){
 
-             if($RequiredFunction.Length -le 0) {
 
-                 Trace-VerboseMessage "Function not contains dependent functions or there is no description of them."
 
-             } else {
 
-                 $DependentFunctions = $RequiredFunction |Select-String -Pattern $fnHelpTemplate -AllMatches |ForEach-Object{$_.Matches|ForEach-Object{$_.Groups['function'].Value}}
 
-             }
 
-         }
 
-         return $DependentFunctions
 
-     }
 
-     function Get-NodePropByName {
 
-         # extract group property
 
-         [OutputType([Hashtable])]
 
-         Param(
 
-             [Parameter(Mandatory=$True)][System.Xml.XmlDocument]$Xml,
 
-             [Parameter(Mandatory=$True)][String]$Path
 
-         )
 
-         $query = "Nodes/Node[@path='$Path']"
 
-         $Node = New-Object System.Collections.Hashtable
 
-         ($xml | Select-Xml -XPath $query) |%{$_.Node.ChildNodes} |ForEach-Object{
 
-             $Node.Add($_.name,$_.value)
 
-         }
 
-         return $Node
 
-     }
 
-     function Get-ChildNodesMapByPath { 
 
-         # External groups from TrustAccess config xml
 
-         [OutputType([Hashtable])]
 
-         Param(
 
-             [Parameter(Mandatory=$True)][System.Xml.XmlDocument]$Xml,
 
-             [Parameter(Mandatory=$True)][String]$Path
 
-         )
 
-         $query = "Nodes/Node[starts-with(@path,'$Path')][a]"
 
-         $Nodes = New-Object System.Collections.Hashtable
 
-         $Path | Trace-Message
 
-         try {
 
-             ($xml | Select-Xml -XPath $query) |%{$_.Node.Path} |Where-Object{$_ -ne "$Path"} |ForEach-Object{
 
-                 $Nodes.Add($_.replace("$Path",'').trim('\'), (Get-NodePropByName -Xml $Xml -Path $_) )
 
-             }
 
-         }
 
-         Catch{
 
-             "Not found ChildNodes from Root Node $Path" | Trace-Message
 
-         }
 
-         return $Nodes
 
-     }
 
-     function Get-NodesMapByPath {
 
-         # Extract root node from Auth.xml
 
-         Param(
 
-             [Parameter(Mandatory=$True)][System.Xml.XmlDocument]$Xml,
 
-             [Parameter(Mandatory=$True)][String]$Path
 
-         )
 
-         $Nodes = New-Object System.Collections.Hashtable
 
-         (Get-RootNodesByPath -Xml $xml -Path $Path) |ForEach-Object{
 
-             $Nodes.Add($_, (Get-ChildNodesMapByPath -Xml $Xml -Path $_) ) # ìîæåò óáðàòü óäàëåíèå ñëåøåé íà êîíöàõ
 
-         }
 
-         return $Nodes
 
-     }
 
-     function Get-RootNodesByPath {
 
-         # Extract root node from Auth.xml
 
-         [OutputType([Hashtable])]
 
-         Param(
 
-             [Parameter(Mandatory=$True)][System.Xml.XmlDocument]$Xml,
 
-             [Parameter(Mandatory=$True)][String]$Path
 
-         )
 
-         $res = @()
 
-         ($xml | Select-Xml -XPath "Nodes/Node[not(a)][@path='$path']")|ForEach-Object{
 
-             $res += $_.Node.Path
 
-         }
 
-         return $res
 
-     }
 
-     function Get-TAusers {
 
-         # return users list from Auth.xml rules
 
-         [OutputType([String[]])]
 
-         Param(
 
-             [Parameter(Mandatory=$True)]
 
-             [ValidateNotNullOrEmpty()]
 
-             [System.Xml.XmlDocument]$Xml
 
-         )
 
-         $res = @()
 
-         ($Xml | Select-Xml -XPath  "Nodes/Node/a[@name='principals' and @value != '']")|ForEach-Object{
 
-             $res += $_.Node.Value
 
-         }
 
-         return $res
 
-     }
 
-     function Get-GroupNodeByRoot {
 
-         # group by the first element in hashtable
 
-         Param(
 
-             [Parameter(Mandatory=$True)][System.Collections.Hashtable]$Nodes
 
-         )
 
-         $Servers = New-Object System.Collections.Hashtable
 
-         $Nodes.Clone().GetEnumerator()|Where-Object{$_.key -notmatch '\\'}|ForEach-Object{
 
-             $root = $_
 
-             $Servers.Add($Root.Key,$Root.Value)
 
-             $Nodes.GetEnumerator()|Where-Object{$_.key -match "$($root.key)\\*"}|ForEach-Object{
 
-                 $Servers[$Root.Key].Add($_.key.replace($root.key,''),$_.Value)
 
-             }
 
-         }
 
-         return $Servers
 
-     }
 
-     function Get-AuthXmlConfiguration {
 
-         <#
 
-             .SYNOPSIS
 
-             Extracts parameters from the Auth.xml
 
-         #>
 
-         [OutputType([Hashtable])]
 
-         Param(
 
-             [Parameter(Mandatory=$True)][String]$AuthXMLPath
 
-         )
 
-         $Authxml = New-Object System.Collections.Hashtable
 
-         $xml = New-Object System.Xml.XmlDocument
 
-         $xml.Load($AuthXMLPath)
 
-         $Authxml.add($GROUPSPATH, (Get-TAConfigNode -Xml $xml -Path $GROUPSPATH) ) 
 
-         $Authxml.add($SYSGROUPSPATH, (Get-TAConfigNode -Xml $xml -Path $SYSGROUPSPATH) ) 
 
-         $Authxml.add($SERVERSPATH , (Get-TAConfigNode -Xml $xml -Path $SERVERSPATH) )
 
-         $Authxml.add($AGENTSPATH, (Get-TAConfigNode -Xml $xml -Path $AGENTSPATH) )
 
-         $Authxml.add($ACCESSRULESPATH, (Get-TAConfigNode -Xml $xml -Path $ACCESSRULESPATH) )
 
-         $Authxml.add($USERSPATH, (Get-TAusers -Xml $xml))
 
-         return $Authxml
 
-     }
 
-     function Get-TAConfigNode {
 
-         # Extract servers from Auth.xml
 
-         Param(
 
-             [Parameter(Mandatory=$True)][System.Xml.XmlDocument]$Xml,
 
-             [Parameter(Mandatory=$True)][String]$Path
 
-         )
 
-         $AuthModCfg = Get-NodesMapByPath -Xml $xml -Path $Path
 
-         Get-GroupNodeByRoot -Nodes $AuthModCfg[$Path]
 
-     }
 
-     function Get-AuthServerQueryArguments {
 
-         <#
 
-             .SYNOPSIS
 
-             Prepare arguments to execute queries on the SNS Security Server.
 
-             .NOTES
 
-             RequiredFunction<Get-PassFromCredential>
 
-             RequiredFunction<Test-isAdmin>
 
-         #>
 
-         [CmdletBinding(DefaultParameterSetName = 'Credentials')]
 
-         Param(
 
-             [Parameter(Mandatory = $True, ParameterSetName = 'builtinAdmin')]
 
-             [String]$SettingskstPath = 'C:\Settings.kst',
 
-             [Parameter(Mandatory = $True, ParameterSetName = 'Credentials')]
 
-             [ValidateNotNullOrEmpty()]
 
-             [System.Management.Automation.PSCredential]$Credential
 
-         )
 
-         $ScSrvConfig = (Get-ItemProperty $Script:AUTHSRVREGPATH).ProductInstallPath + 'ScAuthSrvConfig.exe'
 
-         $Realm = (Get-ItemProperty $Script:AUTHSRVREGPATH).KRBREALM
 
-         if(-not (Test-Path -Path $ScSrvConfig -PathType Leaf) ){throw 'Not found ScAuthSrvConfig.exe util'}
 
-         if($PsCmdlet.ParameterSetName -eq 'builtinAdmin'){
 
-             Try {
 
-                 $builtinAdmin = (Get-Content $SettingskstPath -ErrorAction Stop)[1]
 
-             }
 
-             Catch [Management.Automation.ItemNotFoundException] {
 
-                 Trace-Message -Msg 'Settings.kst file not found!'
 
-                 throw $_
 
-             }
 
-             $ScSrvConfigArg = @('&',"'$ScSrvConfig'", $Realm, '/p', "'$builtinAdmin'")
 
-         } else {
 
-             $ScSrvConfigArg = @('&',"'$ScSrvConfig'", $Realm, '/a', "'$($env:USERNAME)'" ,'/p', "'$(Get-PassFromCredential -Credential $Credential)'")
 
-         }
 
-         return ($ScSrvConfigArg -join ' ')
 
-     }
 
-     function Get-LocalServerQueryArguments {
 
-         <#
 
-             .SYNOPSIS
 
-             Extracts parameters from the Auth.xml
 
-         #>
 
-         [OutputType([Hashtable])]
 
-         Param(
 
-             [System.Management.Automation.PSCredential]$Credentials
 
-         )
 
-         $ScSrvConfig = (Get-ItemProperty $Script:NGFWREGPATH ).ProductInstallPath + 'ScLocalSrvConfig.exe'
 
-         if(-not (Test-Path -Path $ScSrvConfig -PathType Leaf) ) {throw 'Not found ScLocalSrvConfig.exe util'}
 
-         $ScSrvConfigArg = @('&',"'$ScSrvConfig'")
 
-         return ($ScSrvConfigArg -join ' ')
 
-     }
 
-     function Get-PassFromCredential {
 
-         Param(
 
-             [Parameter(Mandatory=$True)][System.Management.Automation.PSCredential]$Credentials
 
-         )
 
-         $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Credentials.Password)
 
-         return [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
 
-     }
 
-     function Test-AgentsOnSecurityServer {
 
-         Param(
 
-             [ValidateNotNullOrEmpty()]
 
-             [Parameter(Mandatory=$True)] [String[]]$TAagents,
 
-             [Parameter(Mandatory=$false)] [String[]]$TAagentsFromRule,
 
-             [ValidateNotNullOrEmpty()]
 
-             [Parameter(Mandatory=$True)] [String[]]$AuthSrvAgents
 
-         )
 
-         $TAagents = $TAagents |ForEach-Object{$_.ToUpper()}
 
-         $AuthSrvAgents = $AuthSrvAgents |ForEach-Object{$_.ToUpper()}
 
-         if ($null -ne $TAagentsFromRule){
 
-             $TAagentsFromRule = $TAagentsFromRule |ForEach-Object{$_.ToUpper()}
 
-             $TAagentsFromRule |Where-Object{$AuthSrvAgents -notcontains $_}|ForEach-Object{
 
-                 Write-Warning ("Íå óäàëîñü íàéòè ó÷åòíóþ çàïèñü êîìïüþòåðà {0} èç ïðàâèëà Trust Access â ñïèñêå àãåíòîâ Secret Net Studio. Ïðè ïðîäîëæåíèè òåêóùåå çíà÷åíèå â ïðàâèëå íå áóäåò èçìåíåíî ïðè èìïîðòå." -f $_) -WarningAction Inquire
 
-             } 
 
-         }
 
-         if( ($TAagents |Where-Object{$AuthSrvAgents -notcontains $_}) -eq $null ){
 
-             Trace-VerboseMessage -Msg "Íàéäåíû âñå àãåíòû èç êîíôèãóðàöèè TrustAccess íà Ñåðâåðå áåçîïàñíîñòè Secret Net Studio."
 
-         } else {
 
-             throw "Imported accounts from TrustAccess weren’t found in the Security Server"
 
-         }
 
-     }
 
-     function Test-TAUsersFromRulesInAD {
 
-         <#
 
-             checking users from the rules in active directory.
 
-         #>
 
-         # check fallback group
 
-         $res = Get-ObjectOnAD -TAGroups $Script:FallBackGroup -DCSession $Script:DCSESSION
 
-         if ($Script:FallBackGroup -ne $Everyone -and ($null -eq $res -or (($res |Where-Object{$_.ObjectClass -eq 'group'}) -eq $null)) ) {Throw 'Çàäàííàÿ ãðóïïà ïî óìîë÷àíèþ îòñóòñòâóåò â AD.'}
 
-         # users from rules
 
-         $TAusersFromRule = Get-TAItem -AuthXml $Script:AUTHXML -Path $script:USERSPATH
 
-         # computers form rules
 
-         $TApcFromRule = $TAusersFromRule |Where-Object{$_ -match '.+\$@.+'}|ForEach-Object{($_ -split '$')[0]}
 
-         # Groups TA add up with users from the rules.
 
-         $TAgoups = ( (Get-TAItem -AuthXml $Script:AUTHXML -Path $script:GROUPSPATH) + ($TAusersFromRule |Where-Object{$_ -notmatch '.+\$@.+'} |ForEach-Object{($_ -split '@')[0]}) |Select-Object -Unique )
 
-         $TAgoups = $TAgoups |%{$_.ToUpper()}
 
-         # Check the groups mapping  from the groups mapping file   
 
-         if ($Script:GroupMappingFile){
 
-             $GroupMappingFromFile = New-Object System.Collections.Hashtable
 
-             try {
 
-                 $GMFileContent = Get-Content -Path $Script:GroupMappingFile -ErrorAction Stop
 
-             }
 
-             Catch {
 
-                 throw 'Íå óäàëîñü ïðî÷èòàòü ôàéë ñîîòâåòñòâèÿ ãðóïï TrustAccess ãðóïïàì â AD.'
 
-             }
 
-             $GMFileContent |ForEach-Object{
 
-                 $item = $_ -split ','
 
-                 $GroupMappingFromFile.Add($item[0].toUpper(), $item[1].toUpper())
 
-             }
 
-             # Check group from group mapping file on AD
 
-             $TAgoups |Where-Object {$GroupMappingFromFile.Keys -contains $_} |Where-Object {$Script:AUTHXML[$SYSGROUPSPATH].Keys  -notcontains $_ }|ForEach-Object {
 
-                 $MappedGroup = $GroupMappingFromFile[$_]
 
-                 if(Test-ObjectOnAD -TAGroups $MappedGroup -DCSession $Script:DCSESSION){
 
-                     Trace-Message -Msg ('User {0} from user mapping file found in Acrive Directory. Trust Access user {1}' -f $MappedGroup, $_)
 
-                     $Script:GROUPMAPPING.Add($_, $MappedGroup)
 
-                 } else {
 
-                     Write-Warning ("Óêàçàííîå â ôàéëå ñîîòâåòñòâèå ïîëüçîâàòåëÿ èëè ãðóïïû TA íå íàéäåíî â Active Directory. Ïðè ïðîäîëæåíèè òåêóùåå çíà÷åíèå {0} áóäåò çàìåíåíî íà ãðóïïó ïî óìîë÷àíèþ {1}." -f $_, $Script:FallBackGroup) -WarningAction Inquire
 
-                     Trace-Message -Msg ('User {0} from user mapping file not found in Acrive Directory, replace to default user {1}' -f $_, $Script:FallBackGroup)
 
-                     $Script:GROUPMAPPING.Add($_, $Script:FallBackGroup)
 
-                 }
 
-             }
 
-             # For users not found from groupmapping file set the fallback group.
 
-             [String[]]$notMappedUser = $TAgoups |Where-Object {$GroupMappingFromFile.Keys -notcontains $_}
 
-             if ($notMappedUser.Length -ge 1){
 
-                 Trace-Message -Msg ("The groups from Trust Access missing in the mapping file are found: `r`n{0}" -f ($notMappedUser -join "`r`n") )
 
-                 $notMappedUser |ForEach-Object{
 
-                     if(Test-ObjectOnAD -TAGroups $_ -DCSession $Script:DCSESSION){
 
-                         Trace-Message -Msg ('User {0} from rule Trust Access found in Acrive Directory.' -f $_)
 
-                         $Script:GROUPMAPPING.Add($_, $_)
 
-                     } else {
 
-                         Write-Warning ("Íå óäàëîñü íàéòè ïîëüçîâàòåëÿ èëè ãðóïïó â ôàéëå ñîîòâåòñòâèÿ è AD. Ïðè ïðîäîëæåíèè òåêóùåå çíà÷åíèå {0} áóäåò çàìåíåíî íà ãðóïïó ïî óìîë÷àíèþ {1}." -f $_, $Script:FallBackGroup) -WarningAction Inquire
 
-                         Trace-Message -Msg ("Replace user {0} from Trust Access to default user {0}." -f $_, $Script:FallBackGroup) 
 
-                         $Script:GROUPMAPPING.Add($_, $Script:FallBackGroup)
 
-                     }
 
-                 }
 
-             } else {
 
-                 Trace-Message -Msg 'All users found in the user mapping file.'
 
-             }
 
-         } else {
 
-             # not net groupmapping file
 
-             $TAgoups |ForEach-Object{
 
-                 if(Test-ObjectOnAD -TAGroups $_ -DCSession $Script:DCSESSION){
 
-                     Trace-Message -Msg ('User {0} from rule Trust Access found in Acrive Directory.' -f $_)
 
-                     $Script:GROUPMAPPING.Add($_, $_)
 
-                 } else {
 
-                     Write-Warning ("Íå óäàëîñü íàéòè ïîëüçîâàòåëÿ èëè ãðóïïó Trust Access â Active Directory. Ïðè ïðîäîëæåíèè òåêóùåå çíà÷åíèå {0} áóäåò çàìåíåíî íà ãðóïïó ïî óìîë÷àíèþ {1}." -f $_, $Script:FallBackGroup) -WarningAction Inquire
 
-                     Trace-Message -Msg ("Replace user {0} from Trust Access to default user {0}." -f $_, $Script:FallBackGroup) 
 
-                     $Script:GROUPMAPPING.Add($_, $Script:FallBackGroup)
 
-                 }
 
-             }
 
-         }
 
-     }
 
-     function Test-ObjectOnAD {
 
-         Param(
 
-             [ValidateNotNullOrEmpty()]
 
-             [Parameter(Mandatory=$True, ValueFromPipeline=$true)]
 
-             [String[]] $TAgroups,
 
-             [ValidateNotNullOrEmpty()]
 
-             [Parameter(Mandatory=$True)]
 
-             [System.Management.Automation.Runspaces.PSSession] $DCSession,
 
-             [Parameter(Mandatory=$false)]
 
-             [String] $DC = ($DCSession.ComputerName)
 
-         )
 
-         Process {
 
-             $TAgroups |ForEach-Object{
 
-                 $res = Get-ObjectOnAD -TAgroups $_ -DCSession $DCSession -DC $DC
 
-                 return ($null -ne $res)
 
-             }
 
-         }
 
-     }
 
-     function Get-ObjectOnAD {
 
-         Param(
 
-             [ValidateNotNullOrEmpty()]
 
-             [Parameter(Mandatory=$True, ValueFromPipeline=$true)]
 
-             [String[]] $TAgroups,
 
-             [ValidateNotNullOrEmpty()]
 
-             [Parameter(Mandatory=$True)]
 
-             [System.Management.Automation.Runspaces.PSSession] $DCSession,
 
-             [Parameter(Mandatory=$false)]
 
-             [String] $DC = $DCSession.ComputerName
 
-         )
 
-         Process {
 
-             $TAgroups |ForEach-Object{
 
-                 $user = $_
 
-                 $ErrorActionPreferencePrev = $ErrorActionPreference
 
-                 for ($attempt = 0; $attempt -lt 33; $attempt++ ) {
 
-                     try {
 
-                         $ErrorActionPreference = 'Stop'
 
-                         $res = Invoke-Command -Session $DCSession -ScriptBlock {Get-ADObject -Filter "Name -eq '$($args[0])'" -Server $args[1]} -ArgumentList @($user,$DC)
 
-                         if($null -ne $res){
 
-                             switch ($res.ObjectClass){
 
-                                 'user'{
 
-                                     $res = Invoke-Command -Session $DCSession -ScriptBlock {Get-ADUser -Filter "Name -eq '$($args[0])'" -Server $args[1]} -ArgumentList @($user,$DC)
 
-                                 }
 
-                                 'computer'{
 
-                                     $res = Invoke-Command -Session $DCSession -ScriptBlock {Get-ADComputer -Filter "Name -eq '$($args[0])'" -Server $args[1]} -ArgumentList @($user,$DC)
 
-                                 }
 
-                                 'group' {
 
-                                     $res = Invoke-Command -Session $DCSession -ScriptBlock {Get-ADGroup -Filter "Name -eq '$($args[0])'" -Server $args[1]} -ArgumentList @($user,$DC)
 
-                                 }
 
-                                 default {}
 
-                             }
 
-                         }
 
-                         return $res
 
-                     }
 
-                     Catch [System.Management.Automation.Remoting.PSRemotingTransportException] {
 
-                         $ErrorActionPreference='SilentlyContinue'
 
-                         Trace-VerboseMessage 'Retry invoke command '
 
-                         Start-Sleep -Seconds 1
 
-                     }
 
-                 }
 
-                 $ErrorActionPreference = $ErrorActionPreferencePrev
 
-                 throw 'Årror checking an object in AD.'
 
-             }
 
-         }
 
-     }
 
-     function Test-isAdmin {
 
-         <#
 
-             .SYNOPSIS
 
-             Checks administrator rights.
 
-             .EXAMPLE
 
-             Test-isAdmin -Credentials $PSSession.Runspace.OriginalConnectionInfo.Credential
 
-         #>
 
-         Param(
 
-             [System.Management.Automation.PSCredential]$Credentials = $null
 
-         )
 
-         if($null -ne $Credentials){
 
-             $User = New-Object System.Security.Principal.WindowsIdentity($Credentials.UserName)
 
-         } else {
 
-             $User = [Security.Principal.WindowsIdentity]::GetCurrent()
 
-         }
 
-         if (-not ([Security.Principal.WindowsPrincipal] $User).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
 
-         {
 
-             Trace-ErrorMessage -Msg "You do not have Administrator rights to run this script on the Security Server!`nPlease re-run this script as an Administrator or use -RunAs parameter!"
 
-             return $false
 
-         } else {
 
-             return $true
 
-         }
 
-     }
 
-     function Initialize-Requirements {
 
-         $isAdmin = $false
 
-         switch ($PsCmdlet.ParameterSetName){
 
-             'Remote'{
 
-             }
 
-             'Local' {
 
-                 $Script:SSSNSName = $env:COMPUTERNAME
 
-             }
 
-             default {}
 
-         }
 
-         $Script:AuthXMLpath = (Resolve-Path $Script:AuthXMLpath).Path
 
-         $Script:AUTHXML = Get-AuthXmlConfiguration -AuthXMLPath $Script:AuthXMLpath
 
-         $Script:SSsession = Get-SessionByCredentials -ComputerName $Script:SSSNSName -Credential $Script:CREDENTIALS
 
-         $Script:DCSESSION = Get-SessionByCredentials -ComputerName $Script:DC -Credential $Script:CREDENTIALS
 
-         Invoke-FnRemote -PSSession $Script:SSsession  -FunctionName 'Invoke-RemoteWithArguments' -ArgList @{
 
-             Param = $Script:RemoteGlobalVar
 
-             InvokeExpression = 'Write-Verbose "Set global variable."' 
 
-             Force        = $true
 
-             Scope        = 'Global'
 
-         }
 
-         Invoke-FnRemote -PSSession $Script:DCSESSION  -FunctionName 'Invoke-RemoteWithArguments' -ArgList @{
 
-             Param = $Script:RemoteGlobalVar
 
-             InvokeExpression = 'Write-Verbose "Set global variable."' 
 
-             Force        =  $true
 
-             Scope        = 'Global'
 
-         }
 
-         $isAdmin = Invoke-FnRemoteCommonWrapper -PSsession $Script:SSsession -InvokeExpression 'Test-isAdmin'
 
-         if(-not $isAdmin){throw 'Äëÿ çàãðóçêè ïðàâèë íà ñåðâåð áåçîïàñíîñòè òðåáóþòñÿ ïðàâà àäìèíèñòðàòîðà.'}
 
-         try {
 
-             Invoke-FnRemoteCommonWrapper -PSsession $Script:DCSESSION -InvokeExpression 'Import-RequiredADmodule -PSmodules $PSmodules' -Parameters @{'PSmodules' = $Script:PSmodules} |Trace-VerboseMessage
 
-         }
 
-         Catch [System.IO.FileNotFoundException] {
 
-             throw 'Íå óäàëîñü çàãðóçèòü òðåáóåìûå ìîäóëè íà êîíòðîëëåðå äîìåíà.'
 
-             exit
 
-         }
 
-         Catch {
 
-             throw $_
 
-         }
 
-     }
 
-     function Import-RequiredADmodule {
 
-         <#
 
-             .SYNOPSIS
 
-             Checking for the presence of necessary modules.
 
-         #>
 
-         Param(
 
-             $PSmodules
 
-         )
 
-         Trace-Message -Msg "Loading the module into the session."
 
-         $PSmodules |ForEach-Object {
 
-             if (Get-Module -ListAvailable -Name $_) {
 
-                 Trace-Message -Msg ("{0} module exists." -f $_)
 
-             } else {
 
-                 Try {
 
-                     Trace-Message -Msg ("Try import module {0}" -f $_)
 
-                     Import-Module -Name $_
 
-                 } Catch {
 
-                     throw ("Module {0} not exist." -f $_)
 
-                 }
 
-             }
 
-         }
 
-     }
 
-     function Get-SessionByCredentials {
 
-         Param(
 
-             [String]$ComputerName,
 
-             [System.Management.Automation.PSCredential]$Credential
 
-         )
 
-         Try {
 
-             $session = New-PSSession -ComputerName $ComputerName -Credential $Credential -ErrorAction Stop
 
-         }
 
-         Catch [System.Management.Automation.Remoting.PSRemotingTransportException] {
 
-             throw ("Îïåðàöèÿ íå ìîæåò áûòü âûïîëíåíà - îøèáêà äîñòóïà ê ñåðâåðó {0}.`r`n{1}" -f $ComputerName, $_)
 
-             exit
 
-         } 
 
-         Catch {
 
-             throw $_
 
-         }
 
-         return $session
 
-     }
 
-     function Get-AgentList {
 
-         Param(
 
-             [ValidateNotNullOrEmpty()]
 
-             [Parameter(Mandatory=$True)][String]$ScSrvConfigArg
 
-         )
 
-         [String[]]$output = Invoke-Expression ($ScSrvConfigArg + '/q', '"show computers"')
 
-         if($LASTEXITCODE -ne 0){
 
-             Trace-Message ('Exit code ScAuthSrvConfig: {0}' -f $LASTEXITCODE)
 
-             Trace-Message ( 'ScSrvConfig error: {0}' -f $output)
 
-             throw ('ScSrvConfig error:{0}' -f $LASTEXITCODE)
 
-         }
 
-         Trace-Message 'Get SNS computers.'
 
-         $output |Trace-Message
 
-         if($null -ne $output){
 
-             $index = 0 
 
-             $output |%{$i = 0}{if($_ -like '*computer(s)*'){$index = $i}else{$i++} }
 
-             $Computers = $output[0..($index -2)]|ForEach-Object{($_ -split '\s+')[0].trim()}
 
-         } else {
 
-             throw 'Íå óäàëîñü ïîëó÷èòü ñïèñîê àãåíòîâ Secret Net Studio.'
 
-         }
 
-         return $Computers
 
-     }
 
-     function Get-TAitem {
 
-         [OutputType([String[]])]
 
-         Param(
 
-             [Parameter(Mandatory=$True)][Hashtable]$AuthXml,
 
-             [Parameter(Mandatory=$True)][String]$Path
 
-         )
 
-         $TAitem = New-Object System.Collections.ArrayList
 
-         if($AuthXml[$Path] -is [hashtable]){
 
-             $TAitem = $AuthXml[$Path].GetEnumerator()|ForEach-Object{$_.key |Where-Object{$_ -notmatch '/'}}
 
-         } elseif ($AuthXml[$Path] -is [System.Array]) {
 
-             $TAitem = $AuthXml[$Path]
 
-         }
 
-         return $TAitem
 
-     }
 
-     function Get-AuthSrvConfiguration {
 
-         <#
 
-             .SYNOPSIS
 
-             Get configuration from Auth Server.
 
-             .NOTES
 
-             RequiredFunction<Get-XMLbyPath>
 
-         #>
 
-         Param(
 
-             [ValidateNotNullOrEmpty()]
 
-             [Parameter(Mandatory=$True)][String[]]$AgentNameList,
 
-             [ValidateNotNullOrEmpty()]
 
-             [Parameter(Mandatory=$True)][String]$ScSrvConfigArg
 
-         )
 
-         $tmpdir = new-item -Path (Join-Path ($env:TEMP) ([System.IO.Path]::GetRandomFileName()) ) -type Directory -ErrorAction Stop
 
-         $AgentsRules = New-Object System.Collections.Hashtable
 
-         Trace-Message -Msg "Create temp directory $tmpdir"
 
-         try{
 
-             $AgentNameList |ForEach-Object {
 
-                 $AgentrulesXML = "$($tmpdir.FullName)\$_"
 
-                 Trace-Message -Msg ("Create temp config agent file {0}" -f $AgentrulesXML)
 
-                 Invoke-Expression ( $ScSrvConfigArg + '/q', ('"show raw_configuration /path ""\auth-mod-cfg\servers\{0}\rules"" /file {1} "') -f $_, $AgentrulesXML) |Trace-Message
 
-                 if($LASTEXITCODE -ne 0){
 
-                     Trace-Message ('Exit code ScAuthSrvConfig: {0}' -f $LASTEXITCODE)
 
-                     throw ('ScSrvConfig error:{0}' -f $LASTEXITCODE)
 
-                 }
 
-                 if(Test-Path -Path $AgentrulesXML -PathType leaf ){
 
-                     $AgentsRules.Add($_, (Get-XMLbyPath -XmlPath $AgentrulesXML) )
 
-                 } else {
 
-                     throw 'Âðåìåííûé ôàéë êîíôèãóðàöèè àãåíòà íå íàéäåí.'
 
-                 }
 
-             }
 
-         } Catch {
 
-             Remove-item -Path $tmpdir -Recurse
 
-             throw
 
-         }
 
-         Trace-Message -Msg "Remove temp directory $tmpdir"
 
-         $AgentsRules.Keys |Trace-Message
 
-         Remove-item -Path $tmpdir -Recurse
 
-         return $AgentsRules
 
-     }
 
-     function Set-TAUsersAsEveryone{
 
-         <#
 
-             Set all users from rule Trust Access as everyone.
 
-         #>
 
-         Param(
 
-             [Hashtable]$AuthXml
 
-         )
 
-         # users from rules
 
-         $TAusersFromRule = Get-TAItem -AuthXml $Script:AUTHXML -Path $script:USERSPATH
 
-         # computers from rules
 
-         $TApcFromRule = $TAusersFromRule |Where-Object{$_ -match '.+\$@.+'}|ForEach-Object{($_ -split '$')[0]}
 
-         $TAgoups = ( (Get-TAItem -AuthXml $Script:AUTHXML -Path $script:GROUPSPATH) + ($TAusersFromRule |Where-Object{$_ -notmatch '.+\$@.+'} |ForEach-Object{($_ -split '@')[0]}) |Select-Object -Unique )
 
-         $TAgoups = $TAgoups|%{$_.ToUpper()}
 
-         $TAgoups |Where-Object  {$Script:AUTHXML[$SYSGROUPSPATH] -notcontains $_}|ForEach-Object {
 
-             $Script:GROUPMAPPING.Add($_, $Everyone)
 
-         }
 
-         $AuthXml[$Script:ACCESSRULESPATH].GetEnumerator()|%{$_.value['groups'] = '1';$_.value['principals'] = ""} 
 
-     }
 
-     function Set-AuthSrvConfiguration {
 
-         <#
 
-             .SYNOPSIS
 
-             Set configuration from Auth Server.
 
-         #>
 
-         Param(
 
-             [ValidateNotNullOrEmpty()]
 
-             [Parameter(Mandatory=$True)][Hashtable]$AgentsConfigXML,
 
-             [ValidateNotNullOrEmpty()]
 
-             [Parameter(Mandatory=$True)][String]$ScSrvConfigArg
 
-         )
 
-         $tmpdir = new-item -Path (Join-Path ($env:TEMP) ([System.IO.Path]::GetRandomFileName()) ) -type Directory -ErrorAction Stop
 
-         Trace-Message -Msg "Create temp directory $tmpdir"
 
-         try{
 
-             $AgentsConfigXML.GetEnumerator() |ForEach-Object {
 
-                 $AgentName = $_.Key
 
-                 $AgentrulesXML = "{0}\{1}.xml" -f $tmpdir.FullName, $AgentName
 
-                 Trace-Message -Msg ("Create temp config agent file {0}" -f $AgentrulesXML)
 
-                 $_.Value.Save($AgentrulesXML)
 
-                 Invoke-Expression ( $ScSrvConfigArg + '/q', ('"set raw_configuration {0} "' -f $AgentrulesXML)) |Trace-Message
 
-                 if($LASTEXITCODE -ne 0){
 
-                     Trace-Message ('Exit code ScAuthSrvConfig: {0}' -f $LASTEXITCODE)
 
-                     throw ('ScSrvConfig error:{0}' -f $LASTEXITCODE)
 
-                 }
 
-             }
 
-         } Catch {
 
-             Trace-Message -Msg "Remove temp directory $tmpdir"
 
-             Remove-item -Path $tmpdir -Recurse
 
-             throw $_
 
-         }
 
-         Trace-Message -Msg "Remove temp directory $tmpdir"
 
-         Remove-item -Path $tmpdir -Recurse
 
-     }
 
-     function Set-AuthSrvPolicyConfiguration {
 
-         <#
 
-             .SYNOPSIS
 
-             Set configuration from Auth Server.
 
-         #>
 
-         Param(
 
-             [ValidateNotNullOrEmpty()]
 
-             [Parameter(Mandatory=$True)][String[]]$Agents,
 
-             [ValidateNotNullOrEmpty()]
 
-             [Parameter(Mandatory=$True)][String]$ScSrvConfigArg,
 
-             [ValidateNotNullOrEmpty()]
 
-             [Parameter(Mandatory=$True)][Hashtable]$AuthPolicy
 
-         )
 
-         $Agents|%{
 
-             $agent = $_
 
-             Trace-Message -Msg ("Set policy agent {0}" -f $agent)
 
-             $AuthPolicy.GetEnumerator() |ForEach-Object {
 
-                 Trace-Message -Msg ("Set auth-policy {0} value {1} for agent {2}" -f $_.Key, $_.Value, $agent)
 
-                 Invoke-Expression ( $ScSrvConfigArg + '/q', ('"set cp {0} /{1} {2}"' -f $agent, $_.Key, $_.Value)) |Trace-Message
 
-                 if($LASTEXITCODE -ne 0){
 
-                     Trace-Message ('Exit code ScAuthSrvConfig: {0}' -f $LASTEXITCODE)
 
-                     throw ('ScSrvConfig error:{0}' -f $LASTEXITCODE)
 
-                 }
 
-             }
 
-         }
 
-     }
 
-     function Get-XMLbyPath {
 
-         Param(
 
-             [ValidateNotNullOrEmpty()]
 
-             [Parameter(Mandatory=$True)][String]$XmlPath
 
-         )
 
-         $xml = New-Object System.Xml.XmlDocument
 
-         Trace-Message -Msg ('Load XML {0}' -f $XmlPath)
 
-         $xml.Load($XmlPath)
 
-         return $xml
 
-     }
 
-     function Import-TARules {
 
-         Param(
 
-             [Hashtable]$AuthXml,
 
-             [String]$ScSrvConfigArg
 
-         )
 
-         $ImportedRules = New-Object System.Collections.Hashtable 
 
-         $UsedGuid = New-Object System.Collections.ArrayList
 
-         $AgentsRuleMsgBuff = New-Object System.Collections.Hashtable
 
-         [String[]]$TAagents = Get-TAitem -AuthXml $Authxml -Path $SCript:AGENTSPATH
 
-         [Hashtable]$AgentsConfigXML = Invoke-FnRemoteCommonWrapper -PSsession $Script:SSsession -InvokeExpression 'Get-AuthSrvConfiguration -AgentNameList $AgentNameList -ScSrvConfigArg $ScSrvConfigArg' -Parameters @{
 
-             ScSrvConfigArg   = $ScSrvConfigArg
 
-             AgentNameList    = $TAagents
 
-         }
 
-         $TAagents|ForEach-Object{
 
-             $agent = $_.ToUpper()
 
-             $RuleMsgBuff = New-Object System.Collections.Hashtable
 
-             $AgentsRuleMsgBuff.Add($agent, (New-Object System.Collections.Hashtable))
 
-             $RawAgentRules = ($AuthXml[$Script:SERVERSPATH].GetEnumerator()|?{$_.Value.'server-name' -eq $agent}).Value.GetEnumerator()|?{$_.Name -match '\\rules\\*'}
 
-             $agentRules = New-Object System.Collections.Hashtable 
 
-             $RawAgentRules.GetEnumerator()|ForEach-Object{
 
-                 $agentrule = $_
 
-                 $agentrule.Name |Select-String -Pattern '\\rules\\(?<type>.+)\\(?<guid>.+)' |ForEach-Object{
 
-                     $agentRules[$_.Matches[0].Groups['type'].Value] += @{$agentrule.Value['order'] = (($agentrule.Value['ruleid']|Select-string -Pattern '\\auth-mod-cfg\\accessrules\\(?<guid>.+)\\').Matches[0].Groups['guid'].Value)}
 
-                 }
 
-             }
 
-             $ImportedRules[$agent] += $agentRules
 
-             $ImportedRules[$agent].GetEnumerator()|ForEach-Object{
 
-                 $Rule = $null
 
-                 $type = $_.Name
 
-                 $RuleMsgBuff.Add($type, (New-Object System.Collections.ArrayList)) |Out-Null
 
-                 if ($type -eq 'network-layer-rules'){return} # skip network layer rules
 
-                 [bool]$icmpProtectOn = $false
 
-                 [Microsoft.PowerShell.Commands.SelectXmlInfo]$currSNSRuleBlock = $AgentsConfigXML[$agent] | Select-Xml -XPath ("//Node[@path='{0}']" -f $type) 
 
-                 if( -not $currSNSRuleBlock){
 
-                     $xmlElement = $AgentsConfigXML[$agent] | Select-Xml -XPath "//Node[@path='rules']"
 
-                     $xmlElement |%{$_.Node.AppendChild( (New-XmlNode -XmlDoc $AgentsConfigXML[$agent] -Type "Node" -Attribute "path" -AttributeName $type) )}
 
-                     [Microsoft.PowerShell.Commands.SelectXmlInfo]$currSNSRuleBlock = $AgentsConfigXML[$agent] | Select-Xml -XPath ("//Node[@path='{0}']" -f $type)
 
-                 }
 
-                 [Microsoft.PowerShell.Commands.SelectXmlInfo[]]$order = $currSNSRuleBlock |Select-Xml -XPath "Node[not((a[@name='order' and @value >= 101990] and a[@name='order' and @value <= 101995]) and a[not(@name = 'protocol' and @value = '1')])]/a[@name='order']"
 
-                 $icmpRules = ($currSNSRuleBlock |Select-Xml -XPath "Node[(a[@name='order' and @value >= 101990] and a[@name='order' and @value <= 101995]) and a[not(@name = 'protocol' and @value = '1')]]")
 
-                 if ($null -ne $icmpRules){
 
-                     $icmpProtectOn = $true
 
-                 }
 
-                 if($null -ne $order){
 
-                     [int]$order = ($order|%{$_.Node.Value} |Measure-Object -Maximum).Maximum + 1
 
-                 } else {
 
-                     [int]$order = $Script:ORDERRAGE[$type]
 
-                 }
 
-                 [String[]]$UsedGuid = 0
 
-                 $currSNSRuleBlock |%{$_.Node.ChildNodes} | ForEach-Object{
 
-                     $rule = $_
 
-                     $UsedGuid += $_.path
 
-                 }
 
-                 ($ImportedRules[$agent][$type].GetEnumerator() |Sort-Object -Property name) |%{$_.Value} |ForEach-Object{$i = 0}{
 
-                     $ruleGUID = $_
 
-                     Trace-VerboseMessage -Msg ('Add rule TA guid:{0}' -f $ruleGUID)
 
-                     if($AuthXml[$ACCESSRULESPATH].$ruleGUID['protocol'] -eq '1' -and ($AuthXml[$ACCESSRULESPATH].$ruleGUID['hidden-rule'] -eq '1')){ # îïðåäåëÿþ ñèñòåìíûå ïðàâèëà Icmp
 
-                         if($icmpProtectOn){
 
-                             Trace-VerboseMessage -Msg 'ICMP rules already exist for this agent on the Auth Server, removed rule from the imported.'
 
-                             $ImportedRules[$agent][$type].Remove( ($ImportedRules[$agent][$type].GetEnumerator()|?{$_.Value -eq $ruleGUID}).Key )
 
-                             $AuthXml[$ACCESSRULESPATH].Remove($ruleGUID)
 
-                             return
 
-                         } else {
 
-                             $AuthXml[$ACCESSRULESPATH].$ruleGUID['create-auth-rule'] = "0"
 
-                             $AuthXml[$ACCESSRULESPATH].$ruleGUID['flags'] = "1"
 
-                             $order += 990
 
-                         }
 
-                     } else {
 
-                         $AuthXml[$ACCESSRULESPATH].$ruleGUID['create-auth-rule'] = "1"
 
-                         $AuthXml[$ACCESSRULESPATH].$ruleGUID['flags'] = "0"
 
-                     }
 
-                     $AuthXml[$ACCESSRULESPATH].$ruleGUID['order'] = ($order + $i)
 
-                     $AuthXml[$ACCESSRULESPATH].$ruleGUID['owner'] = $agent
 
-                     switch -regex ($AuthXml[$ACCESSRULESPATH].$ruleGUID['groups']) { # replacing groups in a rule
 
-                         '^\d{1}$' {
 
-                             $gNum = $AuthXml[$ACCESSRULESPATH].$ruleGUID['groups']
 
-                             $AuthXml[$ACCESSRULESPATH].$ruleGUID['groups'] = ""
 
-                             Trace-VerboseMessage -Msg ('System group in the rule: {0}' -f $gNum)
 
-                             $AuthXml[$ACCESSRULESPATH].$ruleGUID['groups'] = '{0000000#-0000-0000-0000-000000000000}'.Replace('#', $gNum)
 
-                         }
 
-                         '^\d{4}$' {
 
-                             $gNum = $AuthXml[$ACCESSRULESPATH].$ruleGUID['groups']
 
-                             $AuthXml[$ACCESSRULESPATH].$ruleGUID['groups'] = ""
 
-                             $ADgroup = $Script:GROUPMAPPING[(($AuthXml[$script:GROUPSPATH].GetEnumerator()|?{$_.Value['SID'] -eq $gNum}).Name).toUpper()]
 
-                             if($ADgroup -eq $Everyone) {
 
-                                 $AuthXml[$ACCESSRULESPATH].$ruleGUID['groups'] = ($Script:GROUPSNAME.GetEnumerator()|?{$_.Value -eq $Everyone}).Name
 
-                             } else {
 
-                                 $ADobj = Get-ObjectOnAD -TAGroups $ADgroup -DCSession $Script:DCSESSION |Where-Object{$_.ObjectClass -eq 'group'}
 
-                                 if($null -eq $ADobj){throw ('Íå óäàëîñü íàéòè ãðóïïó {0} â Active Directory.' -f $ADgroup)}
 
-                                 $sid = $ADobj.SID
 
-                                 Trace-VerboseMessage -Msg ('External group in the rule sid: {0} SID AD: {1}' -f $gNum, $sid)
 
-                                 $AuthXml[$ACCESSRULESPATH].$ruleGUID['external-subjects'] = $sid
 
-                             }
 
-                         }
 
-                         ''{
 
-                             Trace-VerboseMessage -Msg ('No goups')
 
-                         }
 
-                         Default {
 
-                             throw "Unexpected group id."
 
-                         }
 
-                     }
 
-                     switch -regex ($AuthXml[$ACCESSRULESPATH].$ruleGUID['principals']) { # Replacing users and computer accounts in a rule
 
-                         '' {
 
-                             Trace-VerboseMessage -Msg 'No principal in the rule.'
 
-                         }
 
-                         '(.+)\$@.+' {
 
-                             $AuthXml[$ACCESSRULESPATH].$ruleGUID['principals'] = ""
 
-                             $pc = $matches[1].toUpper()
 
-                             $ADobj = (Get-ObjectOnAD -TAGroups $pc -DCSession $Script:DCSESSION |Where-Object{$_.ObjectClass -eq 'computer'})
 
-                             if($null -eq $ADobj){throw ('Íå óäàëîñü íàéòè êîìïüþòåð {0} â Active Directory.' -f $pc)}
 
-                             $pcSID = $ADobj.SID
 
-                             Trace-VerboseMessage -Msg ('Computer account in the rule. SID:{0}' -f $pcSID)
 
-                             $AuthXml[$ACCESSRULESPATH].$ruleGUID['external-subjects'] = $pcSID
 
-                         }
 
-                         '(.[^\$]+)@.+' {
 
-                             $AuthXml[$ACCESSRULESPATH].$ruleGUID['principals'] = ""
 
-                             $ADuser = $Script:GROUPMAPPING[($matches[1].toUpper())]
 
-                             if($ADuser -eq $Everyone) {
 
-                                 $AuthXml[$ACCESSRULESPATH].$ruleGUID['groups'] = ($Script:GROUPSNAME.GetEnumerator()|?{$_.Value -eq $Everyone}).Name
 
-                             } else {
 
-                                 $ADobj = Get-ObjectOnAD -TAGroups $ADuser -DCSession $Script:DCSESSION
 
-                                 if($null -eq $ADobj){throw ('Íå óäàëîñü íàéòè ïîëüçîâàòåëÿ {0} â Active Directory.' -f $ADuser)}
 
-                                 $userSID = $ADobj.SID
 
-                                 Trace-VerboseMessage -Msg ('User account in the rule. SID:{0}' -f $userSID)
 
-                                 $AuthXml[$ACCESSRULESPATH].$ruleGUID['external-subjects'] = $userSID
 
-                             }
 
-                         }
 
-                         Default {}
 
-                     }
 
-                     Set-RuleNode -Xml $AgentsConfigXML[$agent] -TARule $AuthXml[$ACCESSRULESPATH].$ruleGUID -result ([ref]$Rule) -Type $type -UsedGuid $UsedGuid
 
-                     $i++
 
-                     $currSNSRuleBlock |%{$_.Node.AppendChild($Rule)} |Out-Null
 
-                 }
 
-                 if ($Script:OnlyViewRule){
 
-                     ($ImportedRules[$agent][$type].GetEnumerator() |Sort-Object -Property name) |%{$_.Value} |ForEach-Object{
 
-                         $RuleMsgBuff[$type].Add((Get-ngfwrule -TARule $AuthXml[$ACCESSRULESPATH].$_ -Type $type)) |Out-Null
 
-                     }
 
-                 }
 
-             }
 
-             $AgentsRuleMsgBuff[$agent] += $RuleMsgBuff
 
-         }
 
-         if ($Script:OnlyViewRule) {
 
-             Trace-Message ('Íà íà ñåðâåð áåçîïàñòíîñòè Secret Net Studio {0} áóäóò èìïîðòèðîâàíû ñëåäóþùèå ïðàâèëà:' -f $Script:SSsession.ComputerName )
 
-             $AgentsRuleMsgBuff.GetEnumerator()|ForEach-Object{
 
-                 ('Add rule for agent:{0}' -f $_.key)
 
-                 $_.Value.GetEnumerator()|ForEach-Object{
 
-                     ('Type:{0}' -f $_.key)
 
-                     ('Count:{0}' -f $_.Value.Count)
 
-                     $_.Value |Format-Table * -AutoSize |Out-String
 
-                 }
 
-             }
 
-         } else {
 
-             Trace-Message -Msg 'Set configuration.'
 
-             Invoke-FnRemoteCommonWrapper -PSsession $Script:SSsession -InvokeExpression 'Set-AuthSrvConfiguration -AgentsConfigXML $AgentsConfigXML -ScSrvConfigArg $ScSrvConfigArg' -Parameters @{
 
-                 ScSrvConfigArg   = $ScSrvConfigArg
 
-                 AgentsConfigXML  = $AgentsConfigXML
 
-             }
 
-             if($EnableProtectionEveryone){
 
-                 Trace-Message -Msg 'Set everyone policy.'
 
-                 Invoke-FnRemoteCommonWrapper -PSsession $Script:SSsession -InvokeExpression 'Set-AuthSrvPolicyConfiguration -Agents $Agents -AuthPolicy $AuthPolicy -ScSrvConfigArg $ScSrvConfigArg' -Parameters @{
 
-                     ScSrvConfigArg   = $ScSrvConfigArg
 
-                     Agents           = $AgentsConfigXML.Keys
 
-                     AuthPolicy       = @{
 
-                         'auth_rule_gen_skip_everyone' = 0
 
-                     }
 
-                 }
 
-             }
 
-         }
 
-     }
 
-     function  Get-ngfwrule {
 
-         Param(
 
-             [hashtable]$TARule,
 
-             [String]$type
 
-         )
 
-         switch ($type) {
 
-             'network-transport-with-auth-rules' {
 
-                 New-Object -TypeName NGFWNetworkWithAuthRule($TARule)
 
-             }
 
-             'network-transport-rules' {
 
-                 New-Object -TypeName NGFWNetworkTransportRule($TArule)
 
-             }
 
-             'smb-folder-rules'{
 
-                 New-Object -TypeName NGFWSMBRule($TArule)
 
-             }
 
-             'pipe-rules' {
 
-                 New-Object -TypeName NGFWPipeRule($TArule)
 
-             }
 
-             Default {throw ('Òèï ïðàâèë {0} íå ñóùåñòâóåò.' -f $type) }
 
-         }
 
-     }
 
-     function CreateRuleNode{
 
-         Param(
 
-             [Parameter(Mandatory=$True)]
 
-             [System.Xml.XmlDocument]$XmlDoc,
 
-             [String]$Name,
 
-             [String]$Value
 
-         )
 
-         $Field = New-XmlNode -XmlDoc $XmlDoc -Type "a" -Attribute "name" -AttributeName $Name -AttributeValue $Value
 
-         return $Field
 
-     }
 
-     function New-XmlNode {
 
-         Param(
 
-             [Parameter(Mandatory=$True)]
 
-             [System.Xml.XmlDocument]$XmlDoc,
 
-             [Parameter(Mandatory=$True)]
 
-             [String]$Type,
 
-             [Parameter(Mandatory=$True)]
 
-             [String]$Attribute,
 
-             [Parameter(Mandatory=$True)]
 
-             [String]$AttributeName,
 
-             [Parameter(Mandatory=$false)]
 
-             [String]$AttributeValue
 
-         )
 
-         $Field = $XmlDoc.CreateElement($type)
 
-         $Field.SetAttribute($Attribute, $AttributeName)
 
-         $Field.SetAttribute("value",$AttributeValue)
 
-         return $Field
 
-     }
 
-     function Set-RuleNode {
 
-         Param(
 
-         [Parameter(Mandatory=$True)][System.Xml.XmlDocument]$Xml,
 
-         [Parameter(Mandatory=$True)][hashtable]$TARule,
 
-         [Parameter(Mandatory=$True)][String[]]$UsedGuid,
 
-         [Parameter(Mandatory=$True)][String]$Type,
 
-         [Parameter(Mandatory=$True)][ref]$result
 
-         )
 
-         $Rule = $xml.CreateElement("Node")
 
-         do
 
-         {
 
-         $guid = "{$([guid]::NewGuid().guid)}"
 
-         } while($UsedGuid -icontains $guid)
 
-         $Rule.SetAttribute("path", $guid)
 
-         switch ($Type) {
 
-             'network-layer-rules' {
 
-                 Set-NetworkLayerRuleNode -Rule $Rule -TArule $TArule
 
-               }
 
-             'network-transport-with-auth-rules' {
 
-                 Set-TransportWithAuthRuleNode -Rule $Rule -TArule $TArule
 
-             }
 
-             'network-transport-rules' {
 
-                 Set-TransportRuleNode -Rule $Rule -TArule $TArule
 
-             }
 
-             'smb-folder-rules'{
 
-                 Set-SmbRuleNode -Rule $Rule -TArule $TArule
 
-             }
 
-             'pipe-rules' {
 
-                 Set-PipeRuleNode -Rule $Rule -TArule $TArule
 
-             }
 
-             Default {throw ('Òèï ïðàâèë {0} íå ñóùåñòâóåò.' -f $Type) }
 
-         }
 
-         $result.Value = $rule
 
-     }
 
-     function Set-TransportWithAuthRuleNode {
 
-         Param(
 
-             [System.Xml.XmlElement]$Rule,
 
-             [hashtable]$TArule
 
-         )
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "order" -Value ("{0}" -f $TArule["order"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "enabled" -Value ("{0}" -f $TArule["enabled"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "ruletype" -Value ("{0}" -f $TArule["ruletype"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "service" -Value ("{0}" -f $TArule["service"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accesstype" -Value ("{0}" -f $TArule["accesstype"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "audit-enabled" -Value ("{0}" -f $TArule["audit-enabled"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-ports" -Value ("{0}" -f $TArule["local-ports"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-ports" -Value ("{0}" -f $TArule["remote-ports"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "protocol" -Value ("{0}" -f $TArule["protocol"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-addrs" -Value ("{0}" -f $TArule["local-addrs"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-addrs" -Value ("{0}" -f $TArule["remote-addrs"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-direction-type" -Value ("{0}" -f $TArule["rule-direction-type"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "flags" -Value ("{0}" -f $TArule["flags"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "groups" -Value ("{0}" -f $TArule["groups"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "create-auth-rule" -Value ("{0}" -f $TArule["create-auth-rule"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "owner" -Value ("{0}" -f $TArule["owner"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "description" -Value "" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "guid" -Value "" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-activate-times" -Value ("{0}" -f $TArule["rule-activate-times"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd" -Value ("{0}" -f $TArule["on-rule-action-cmd"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-folder" -Value "" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-start-type" -Value "system" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-token-type" -Value "user" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-beep" -Value ("{0}" -f $TArule["on-rule-action-cmd-beep"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accessmask" -Value ("{0}" -f $TArule["accessmask"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "reply-on-reject" -Value ("{0}" -f $TArule["reply-on-reject"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-include" -Value ("{0}" -f $TArule["adapters-to-include"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-exclude" -Value ("{0}" -f $TArule["adapters-to-exclude"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-match" -Value ("{0}" -f $TArule["adapters-match"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-activate-regexp" -Value ("{0}" -f $TArule["rule-activate-regexp"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "principals" -Value ("{0}" -f $TArule["principals"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "external-subjects" -Value ("{0}" -f $TArule["external-subjects"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "restricted-process-sids" -Value "" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "is-emergency-rule" -Value ("{0}" -f $TArule["is-emergency-rule"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "network-level" -Value ("{0}" -f $TArule["network-level"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-scope" -Value ("{0}" -f $TArule["rule-scope"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "out-channel-protection-enabled" -Value ("{0}" -f $TArule["out-channel-protection-enabled"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "processes-to-include" -Value ("{0}" -f $TArule["processes-to-include"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "processes-to-exclude" -Value ("{0}" -f $TArule["processes-to-exclude"]) )) |Out-Null
 
-     }
 
-     function Set-TransportRuleNode {
 
-         Param(
 
-             [System.Xml.XmlElement]$Rule,
 
-             [hashtable]$TArule
 
-         )
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "order" -Value ("{0}" -f $TArule["order"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "enabled" -Value ("{0}" -f $TArule["enabled"]) )) |Out-Null |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "ruletype" -Value ("{0}" -f $TArule["ruletype"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "service" -Value ("{0}" -f $TArule["service"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accesstype" -Value ("{0}" -f $TArule["accesstype"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "audit-enabled" -Value ("{0}" -f $TArule["audit-enabled"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-ports" -Value "" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-ports" -Value "" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "protocol" -Value ("{0}" -f $TArule["protocol"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-addrs" -Value ("{0}" -f $TArule["local-addrs"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-addrs" -Value ("{0}" -f $TArule["remote-addrs"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-direction-type" -Value ("{0}" -f $TArule["rule-direction-type"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "flags" -Value ("{0}" -f $TArule["flags"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-condition" -Value ("{0}" -f $TArule["rule-condition"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "description" -Value "" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "create-auth-rule" -Value ("{0}" -f $TArule["create-auth-rule"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "guid" -Value "" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "owner" -Value ("{0}" -f $TArule["owner"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-activate-times" -Value ("{0}" -f $TArule["rule-activate-times"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd" -Value ("{0}" -f $TArule["on-rule-action-cmd"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-folder" -Value "" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-start-type" -Value "system" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-token-type" -Value "user" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-beep" -Value ("{0}" -f $TArule["on-rule-action-cmd-beep"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accessmask" -Value ("{0}" -f $TArule["accessmask"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "reply-on-reject" -Value ("{0}" -f $TArule["reply-on-reject"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-include" -Value ("{0}" -f $TArule["adapters-to-include"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-exclude" -Value ("{0}" -f $TArule["adapters-to-exclude"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-match" -Value ("{0}" -f $TArule["adapters-match"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-activate-regexp" -Value ("{0}" -f $TArule["rule-activate-regexp"]) )) |Out-Null
 
-     }
 
-     function Set-NetworkLayerRuleNode {
 
-         Param(
 
-             [System.Xml.XmlElement]$Rule,
 
-             [hashtable]$TArule
 
-         )
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "order" -Value ("{0}" -f $TArule["order"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "enabled" -Value ("{0}" -f $TArule["enabled"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "ruletype" -Value ("{0}" -f $TArule["ruletype"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "service" -Value ("{0}" -f $TArule["service"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accesstype" -Value ("{0}" -f $TArule["accesstype"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "audit-enabled" -Value ("{0}" -f $TArule["audit-enabled"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "datalink-protocol" -Value ("{0}" -f $TArule["datalink-protocol"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "network-protocol" -Value ("{0}" -f $TArule["network-protocol"]) )) |Out-Null
 
-     }
 
-     function Set-PipeRuleNode {
 
-         Param(
 
-             [System.Xml.XmlElement]$Rule,
 
-             [hashtable]$TArule
 
-         )
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "order" -Value ("{0}" -f $TArule["order"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "enabled" -Value ("{0}" -f $TArule["enabled"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "ruletype" -Value ("{0}" -f $TArule["ruletype"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "service" -Value ("{0}" -f $TArule["service"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accesstype" -Value ("{0}" -f $TArule["accesstype"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "audit-enabled" -Value ("{0}" -f $TArule["audit-enabled"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-ports" -Value "*" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-ports" -Value "*" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-addrs" -Value ("{0}" -f $TArule["local-addrs"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-addrs" -Value ("{0}" -f $TArule["remote-addrs"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-direction-type" -Value "in" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "flags" -Value ("{0}" -f $TArule["flags"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "description" -Value ("{0}" -f $TArule["description"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "create-auth-rule" -Value "1" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "guid" -Value "" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "owner" -Value ("{0}" -f $TArule["owner"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-activate-times" -Value ("{0}" -f $TArule["rule-activate-times"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd" -Value ("{0}" -f $TArule["on-rule-action-cmd"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-folder" -Value "" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-start-type" -Value "system" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-token-type" -Value "user" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-beep" -Value ("{0}" -f $TArule["on-rule-action-cmd-beep"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accessmask" -Value ("{0}" -f $TArule["accessmask"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "reply-on-reject" -Value ("{0}" -f $TArule["reply-on-reject"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-include" -Value ("{0}" -f $TArule["adapters-to-include"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-exclude" -Value ("{0}" -f $TArule["adapters-to-exclude"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-match" -Value ("{0}" -f $TArule["adapters-match"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "groups" -Value ("{0}" -f $TArule["groups"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "principals" -Value ("{0}" -f $TArule["principals"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "external-subjects" -Value ("{0}" -f $TArule["external-subjects"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "restricted-process-sids" -Value "" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "is-emergency-rule" -Value "0" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "pipe-name" -Value ("{0}" -f $TArule["pipe-name"]) )) |Out-Null
 
-     }
 
-     function Set-SmbRuleNode {
 
-         Param(
 
-             [System.Xml.XmlElement]$Rule,
 
-             [hashtable]$TArule
 
-         )
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "order" -Value ("{0}" -f $TArule["order"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "enabled" -Value ("{0}" -f $TArule["enabled"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "ruletype" -Value ("{0}" -f $TArule["ruletype"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "service" -Value ("{0}" -f $TArule["service"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accesstype" -Value ("{0}" -f $TArule["accesstype"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "audit-enabled" -Value ("{0}" -f $TArule["audit-enabled"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-ports" -Value "" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-ports" -Value "" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "local-addrs" -Value ("{0}" -f $TArule["local-addrs"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "remote-addrs" -Value ("{0}" -f $TArule["remote-addrs"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-direction-type" -Value "in" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "flags" -Value ("{0}" -f $TArule["flags"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "description" -Value "" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "create-auth-rule" -Value "1" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "guid" -Value "" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "owner" -Value ("{0}" -f $TArule["owner"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "rule-activate-times" -Value ("{0}" -f $TArule["rule-activate-times"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd" -Value ("{0}" -f $TArule["on-rule-action-cmd"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-folder" -Value "" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-start-type" -Value "system" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-token-type" -Value "user" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "on-rule-action-cmd-beep" -Value ("{0}" -f $TArule["on-rule-action-cmd-beep"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "accessmask" -Value ("{0}" -f $TArule["accessmask"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "reply-on-reject" -Value ("{0}" -f $TArule["reply-on-reject"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-include" -Value ("{0}" -f $TArule["adapters-to-include"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-to-exclude" -Value ("{0}" -f $TArule["adapters-to-exclude"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "adapters-match" -Value ("{0}" -f $TArule["adapters-match"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "groups" -Value ("{0}" -f $TArule["groups"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "principals" -Value ("{0}" -f $TArule["principals"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "external-subjects" -Value ("{0}" -f $TArule["external-subjects"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "restricted-process-sids" -Value "" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "is-emergency-rule" -Value "0" )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "folder-path-mask" -Value ("{0}" -f $TArule["folder-path-mask"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "include-subfolders" -Value ("{0}" -f $TArule["include-subfolders"]) )) |Out-Null
 
-         $Rule.AppendChild((CreateRuleNode -XmlDoc $xml -Name "file-name-masks" -Value ("{0}" -f $TArule["file-name-masks"]) )) |Out-Null
 
-     }
 
-     Initialize-Requirements
 
-     if ($PSBoundParameters['OnlyCurrentComputer']) {
 
-         $Script:ScSrvConfigArg = Get-LocalServerQueryArguments 
 
-         if( (Get-TAItem -AuthXml $Script:AUTHXML -Path $script:AGENTSPATH|?{$_.ToUpper() -eq $env:COMPUTERNAME}) -ne $null){ 
 
-             $item = $AUTHXML[$AGENTSPATH].GetEnumerator()|?{$_.Key -eq $env:COMPUTERNAME} 
 
-             $AUTHXML[$AGENTSPATH] = @{$item.Key = $item.Value}
 
-             Set-TAUsersAsEveryone -AuthXML $AuthXml
 
-         } else {
 
-             throw 'Íå óäàëîñü íàéòè òåêóùåå èìÿ êîìïüþòåðà â ñïèñêå àãåíòîâ êîíôèãóðàöèè Trust Access.'
 
-         }
 
-     } else {
 
-         $Script:ScSrvConfigArg = Invoke-FnRemoteCommonWrapper -PSsession $Script:SSsession -InvokeExpression 'Get-AuthServerQueryArguments -credential $Credential' -Parameters @{
 
-             Credential   = $Script:CREDENTIALS
 
-         }
 
-         $SNSagents =  Invoke-FnRemoteCommonWrapper -PSsession $Script:SSsession -InvokeExpression 'Get-AgentList -ScSrvConfigArg $ScSrvConfigArg' -Parameters @{
 
-             ScSrvConfigArg   = $ScSrvConfigArg
 
-         }
 
-         $TApcFromRule = (Get-TAItem -AuthXml $Script:AUTHXML -Path $script:USERSPATH) |Where-Object{$_ -match '.+\$@.+'}|ForEach-Object{($_ -split '\$')[0]}
 
-         Test-TAUsersFromRulesInAD
 
-         Test-AgentsOnSecurityServer -TAagents (Get-TAItem -AuthXml $Authxml -Path $script:AGENTSPATH) -AuthSrvAgents $SNSagents -TAagentsFromRule $TApcFromRule
 
-     }
 
-     Import-TARules -AuthXML $AuthXml -ScSrvConfigArg $ScSrvConfigArg
 
-     Trace-message -Msg 'End.'
 
- }
 
- End {
 
-     Remove-ScriptVariable
 
- }
 
 
  |