Working with Active Directory from Powershell using .Net

By Andrei Ungureanu - Last updated: Wednesday, July 23, 2014

De cand cu Windows 2012, nevoia de a apela direct la .Net sau ADSI pentru interactiunea cu Active Directory s-a redus foarte mult, dar inca mai sunt momente cand nu gasim cmdlet-ul potrivit pentru un anumit task. Sau cand pe sistemul de pe care lucram nu avem la dispozitie noile cmdlet-uri sau avem un script pe care dorim sa il facem cat mai portabil.

Daca ai .Net pe sistemul de pe care rulezi scriptul, atunci nu mai ai nevoie de nimic altceva. Exista 3 namespace-uri de interes pentru lucrul cu Active Directory:

System.DirectoryServices.DirectoryEntry – folosit pentru a crea obiecte noi in AD

System.DirectoryServices.DirectorySearcher – are tot ce trebuie pentru a efectua cautari

System.DirectoryService.ActiveDirectory – cu namespace-ul asta te ocupi de management-ul AD-ului si o sa-l folosim ca exemplu pentru ca e cel mai important pentru un admin.

De exemplu folosind urmatoarea sintaxa putem afla detalii despre forestul actual:

$forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()

image

Iar cu Get-Member putem vedea proprietatile si metodele obiectului rezultat:

image

Dupa cum se poate vedea exista chiar si metoda pentru RaiseForestFunctionality sau GetAllTrustRelationships. Sau proprietatea numita Sites care ne va lista toate site-urile din forest.

image

Dar hai sa luam exemplu in care dorim sa ne conectam la un anumit domeniu. Pentru asta exista clasa Domain si metoda GetDomain. Treaba e ca GetDomain accepta un obiect de tip DirectoryContext:

$dscontext = New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext(‘Domain’, "winadmin.local")

image

Odata obtinut DirectoryContext putem folosi metoda GetDomain.

$domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($dscontext)

image

Iata ce ne arata si un Get-Member:

image

Dar astea sunt doar cateva exemple. Daca stati sa studiati documentatia de pe MSDN pentru aceste clase veti observa ca puteti face aproape orice via .Net, sa fortati replicari, KCC, sa creati trust-uri, sa verificati status-ul replicarilor in AD si multe altele.

PS: Tineti minte ca de fiecare data cand este posibil este mai bine sa folositi cmdlet-urile deja existente.

Filed in Active Directory, Scripting • Tags: ,

Debug Diagnostic Tool

By Andrei Ungureanu - Last updated: Wednesday, July 23, 2014

Chiar daca initial Debug Diagnostic Tool a fost conceput pentru a investiga probleme de IIS, versiunea actuala se poate descurca cu orice problema din user mode.

Poate deveni foarte util atunci cand investigati un memory leak sau un crash in user mode (bineinteles ca puteti face asta si cu ADPlus dar exista cateva avantaje cu acest tool, in special legate de monitorizarea proceselor ce se afla sub investigatie).

Noua versiune o gasiti in link-ul de mai jos:

http://www.microsoft.com/en-us/download/confirmation.aspx?id=42933

Iar aici gasiti o pagina cu link-uri catre tutoriale:

http://blogs.msdn.com/b/asiatech/archive/2014/02/26/using-debug-diagnostic-tool-v2-0-to-troubleshoot-iis-problems.aspx

Sau blog-ul echipei ce a dezvoltat tool-ul:

http://blogs.msdn.com/b/debugdiag/

Filed in Windows Client, Windows Server • Tags:

Powershell Here-strings

By Andrei Ungureanu - Last updated: Tuesday, July 22, 2014

Here-Strings este o functionalitate a Powershell-ului ce permite lucrul cu blocuri de text intr-un mod foarte simplu fara a fi nevoie de alte taskuri suplimentare pentru a formata textul.

Tot ce este nevoie este sa puneti textul asa cum vreti sa arate. Conditia este ca linia de inceput trebuie sa contina @” (si atat, nimic altceva pe aceasta linie) iar linia de final “@.

$text = @"
This is a string
…………….
…………….
      END
"@

image

Poate fi foarte util atunci cand aveti un output mai sofisticat sau poate cand vreti sa trantiti undeva niste fisiere de configurare, sau vreun html/xml. Puteti sa aveti ghilimele sau apostrof si nu este nevoie sa faceti escape.

Variablilele vor fi expandate in continuare si in here-strings; de exemplu mai jos ma folosesc de get-date pentru a insera data curenta in continut.

$text = @"
  Data de azi este
   $(get-date )
"@

 

image

Sau o alta forma ar fi:

$text = @"
  Data de azi este
   {0}
"@ –f $(get-date)

Filed in Scripting • Tags:

Kerberos Preauthentication

By Andrei Ungureanu - Last updated: Friday, July 18, 2014

Tocmai ce am gasit intr-un AD setarea Do not require Kerberos preauthentication activata pe cateva conturi de user.

image

Tot ce imi vine in  minte este ca cineva a incercat ceva in timpul unui proces de troubleshooting ca altfel nu inteleg. Si sincer pana acum nu am dat de nici un environment cu Windows care sa necesite aceasta setare. Prin documentatie se mai spune ca ar fi utila cand te lupti cu unele implementari de kerberos vechi de cand lumea si pamantul dar tot nu am vazut.

Dar sa explic si ce face setarea ca sa intelegeti ca nu este bine sa o aveti setata pe nici un cont.

In timpul procesului de autentificare via Kerberos, unul dintre primii pasi este de a cere de la KDC un ticket TGT ce ii va permite sa discute in continuare cu KDC-ul. Dar inainte de asta clientul trimite un AS request prin care se identifica si semneaza si un timestamp cu propria parola. Cum KDC-ul are acces la parola utilizatorului, va putea sa verifice timestampul si automat sa valideze identitatea userului. Userul fiind autentificat, va primi TGT-ul.

Do not require Kerberos preauthentication dezactiveaza acest proces. Doar spui ca esti Gigel, te crede pe cuvant, si primesti TGT-ul.

Periculos, nu-i asa?

Filed in Active Directory • Tags:

Allbootdisks

By Andrei Ungureanu - Last updated: Friday, July 18, 2014

In caz ca aveti nevoie de un ISO cu DOS sau Win95/98 puteti sa gasiti aici:

http://www.allbootdisks.com/download/iso.html

Mai departe puteti sa folositi Rufus (http://rufus.akeo.ie/) pentru a face un USB bootabil.

Sunt utile cand vrei sa mai faci un firmware update etc.

Filed in Diverse • Tags:

You’re the expert, can you or can you not do this?

By Andrei Ungureanu - Last updated: Thursday, July 17, 2014

Sa ne mai si amuzam putin:

http://www.wimp.com/theexpert/

Filed in IT Fun

Powershell 5.0

By Andrei Ungureanu - Last updated: Thursday, July 17, 2014

Se discuta de ceva timp de Powershell 5.0 si imi pare rau ca nu am apucat sa pomenesc din timp de el. Cel mai aprig se pomeneste despre OneGet, PowerShellGet dar si DSC (cunoscut deja din versiunea anterioara).

Daca sunteti curiosi si vreti sa il incercati puteti sa luati versiunea beta de aici:

http://www.microsoft.com/en-us/download/details.aspx?id=42936

Sper ca in curand sa imi fac timp si sa scriu cate ceva despre OneGet si PowerShellGet.

Filed in Scripting, Windows Server • Tags:

AD ACL Scanner

By Andrei Ungureanu - Last updated: Tuesday, July 15, 2014

Tin minte ca acum multi ani pusesem la dispozitie cateva scripturi pentru a ajuta la localizarea locurilor din AD unde au fost setate delegari.

Mai nou, exista un script (e scris in Powershell si are si interfata grafica) facut de un angajat MS ce va poate ajuta sa documentati foarte usor permisiunile din Active Directory.

Se numeste AD ACL Scanner si il puteti downloada de aici: https://adaclscan.codeplex.com/

Bineinteles ca fiind un script powershell va fi nevoie sa aveti execution policy setat pe unrestricted (Set-ExecutionPolicy Unrestricted). Odata rulat interfata arata asa:

image

Optiunea default in Scan Depth este base adica va scana doar containerul selectat, dar puteti selecta subtree si va lua la verificat toate containerele de sub el pentru un raport complet. Bineinteles ca exista si optiunea de a scana alte tipuri de obiecte, nu doar OU-uri.

image

Daca selectati optiunea SD Modified Date veti putea vedea si data cand ACL-ul a fost modificat:

image

Alte functionalitati importante ar fi optiunea de filtrare dupa un anumit obiect sau user, optiunea de a compara raportul actual cu unul mai vechi (pentru a observa schimbarile) si functionalitatea de export in CSV.

Mai jos iata un exemplu in care caut delegarile din tot domeniul pentru un anumit utilizator:

image

image

Asa ca nu mai stati pe ganduri, folositi scriptul pentru a va pune in ordine documentatia pentru AD.

PS: are si functia pe care o facusem eu via vbscript de a gasi inheritance disabled (obiectele cu inheritance disabled vor fi marcate cu rosu in raport).

Filed in Active Directory • Tags: ,

Group Policy Debugging with Policy Reporter

By Andrei Ungureanu - Last updated: Monday, July 14, 2014

Daca tot am povestit despre Gpsvc.log cred ca merita sa arat si o metoda mai usoara de investigatie, folosind un tool numit Policy Reporter.

Policy Reporter se bazeaza pe informatiile din Gpsvc.log si registry (pentru tab-ul History) si poate analyza log-ul de pe un sistem local sau de pe unul remote.

Iata cum arata in actiune:

image

Foarte multe nu sunt de spus sau de explicat pentru ca de aici incolo depinde doar de skill-urile voastre de troubleshooting si de cum veti reusi sa folositi informatia pusa la dispozitie.

De retinut este ca Policy Reporter va poate ajuta sa vizualizati mai usor informatiile legate de procesarea GPO-urilor si e bine sa-l aveti in lista de unelte pentru troubleshooting.

Filed in Active Directory • Tags:

Tot despre Windows Clustering si Persistent & Autostart

By Andrei Ungureanu - Last updated: Friday, July 11, 2014

Scriam aici despre cele doua setari Persistent si Autostart, dar am gasit o explicatie mult mai buna si mai acurata decat ce am spus eu acolo pe blogul celor de la Clustering and High Availability. De retinut ca Persistent mode nu retine numai locatia unde resursa a fost online, ci si starea acesteia (online sau offline) ceea ce va activa si startup-ul odata cu clusterul.

· Auto Start

o Determines if a group will start automatically when starting a cluster or recovering after a failure

o Failover Cluster Manager: Auto start

o PowerShell & Cluster API: Priority

· Persistent Mode

o When enabled, this remembers the last node the administrator onlined a group on, or moved a group to. The group will be hosted on this “default” node on next cluster cold start.

o Failover Cluster Manager: Enable Persistent Mode

o PowerShell & Cluster API: DefaultOwner

· Group Wait Delay

o Specifies the amount of time groups will wait for their default or preferred owner node to come up during cluster cold start, before the groups are moved to another node.

o PowerShell & Cluster API: ClusterGroupWaitDelay

 

Auto-Start

This setting is intended to delay lower priority roles from recovering after failures, in order to allow higher priority groups to take the necessary system resources to come online successfully. This may be particularly useful in Hyper-V clusters, where administrators may want to keep lower priority virtual machines offline, to give higher priority virtual machines a better chance to come online faster when the cluster is started or after failure recovery. Note that administrator action is required after each and every failure of groups not marked with “Auto Start” to bring them back online.

By default, cluster roles have this setting enabled. To disable auto-start for a group (changing it low-priority), do the following in Failover Cluster Manager:

1. In the tree view, select the group under Services and applications

2. In the Actions pane, select Properties

3. Deselect the “Auto start” checkbox

Effects of Disabling Auto Start

When Auto Start is disabled, after failure of any resource in the group, that group will remain in a failed state and not come online. As a result, low-priority groups will not failover due to resource failures. On group failover due to node failure, the group will remain offline regardless its previous state. When cluster cold starts, the group will stay offline as well. The administrator will need to either manually online or move the group to bring it back online.

If the administrator manually moves a group, whether its resources come online depends on their persistent state. The persistent state of a resource simply reflects the last resource state set by the administrator (either online or offline), and the cluster will maintain that state when possible. The persistent state is automatically set when the administrator manually onlines or offlines a group or resource. So if the administrator never brought a group online, or previously offlined the group without bringing it back online, the group will stay offline after a manual move. However, if the administrator brought the group online at some point, but the group became failed or offline due to resource or node failure, manually moving the group will also bring it online.

If one or more preferred owners are set, and failback is enabled for the group, the group will come online as normal after failback—as if it were manually moved. Because a group could be online before failback, and failback is an administrator-defined policy to automatically move groups to a more preferred node when available, failback is more useful when a group is kept online.

Persistent Mode

This mode is intended to allow groups to come online on the node which an admin last moved them to. By default, cluster roles have this setting disabled, except for Hyper-V virtual machine cluster roles, which have this enabled by default. This setting is useful when the cluster is shutdown and later started, in order to better distribute the resources across the nodes and allow them to come online faster, as they were likely spread across the nodes before the cluster was offlined. Otherwise, all the resources will attempt to restart on the first nodes which achieve quorum and compete for resources. This only applies to a group if it did not failover after being placed by the administrator. If a group has failed over since the last administrator placement, it is brought online on the node which the administrator last move it to.

To enable persistent mode for a group, do the following in Failover Cluster Manager:

1. In the tree view, select the group under Services and applications

2. In the Actions pane, select Properties

3. Select the “Enable persistent mode” checkbox

Effects of Persistent Mode

On a cluster cold start, any group with persistent mode enabled will wait for and come online on its “default node”, which is the last node the administrator moved the group to, or onlined the group on. If the administrator last moved the group to a “best possible” node, the cluster will manage group placement and the default node is cleared. Note that if the group’s preferred owners are defined, the preferred owners take precedence over the default owner. The default owner behaves as if it were the last preferred owner—the group would be placed there if it could not be placed on any of its preferred owners.

This mode has no effect on group failover or other moves.

To prevent groups from waiting indefinitely for their preferred or default owner nodes, the group wait delay can be configured. However, with a larger numbers of groups, it takes longer for nodes to join, and the group wait delay may need to be increased, which is discussed in the next section.

Group Wait Delay

This setting only applies during a cluster cold start, and is intended to allow administrators to balance the amount of time groups stay in Pending state while waiting for their preferred or default owner nodes to come online. Increased wait delay causes groups to take longer to come online, but also increases the likelihood that groups will actually be hosted on their preferred or default owner nodes. The default value for the Group Wait Delay is 30 seconds.

This setting applies only to groups that have preferred or default owners specified. Such group could come online on any of its preferred or default owner nodes that come up within the group wait delay.

This is a cluster-wide property ClusterGroupWaitDelay can be configured using PowerShell:

PS> (Get-Cluster <clustername>).ClusterGroupWaitDelay = <time in seconds>

For example, to change this setting on a cluster named “Cluster1” to 300 seconds, use the command:

PS> (Get-Cluster Cluster1).ClusterGroupWaitDelay = 300

It is also important to keep in mind that the cluster service start time can be affected by hardware, system resources, the number of groups, and other factors, so you may need to make further adjustments.

Filed in Windows Server • Tags: