Mostrando postagens com marcador Active Directory. Mostrar todas as postagens
Mostrando postagens com marcador Active Directory. Mostrar todas as postagens

Restaurar perda de confiança com o domínio

 

Windows 10/11/2019/2022/2025

Com o Windows 10, existem várias soluções para resolver o problema, que veremos aqui.
Reset-ComputerMachinePassword

A primeira solução será usar o cmdlet Reset-ComputerMachinePassword que redefine a senha da conta do computador, o que resolve o problema.

1. Faça login com uma conta de administrador local

2. Inicie uma janela de comando do PowerShell como administrador

3. Digite o seguinte comando:

Reset-ComputerMachinePassword -Server "SERVER_DC" -Credential compte-admin@domaine.local

4. Reinicie o computador. 



Test-ComputerSecureChannel

A outra solução para resolver o problema de aprovação é usar o cmdlet Test-ComputerSecureChannel com o parâmetro -repair

1. Faça logon no computador (de preferência com a conta de administrador local).

2. Abra um prompt de janela do PowerShell como administrador.

3. Digite o seguinte cmdlet para reparar a “ligação segura”.

Test-ComputerSecureChannel -Repair -Credential admin-on-domain@domain.local

Digite a senha vinculada à conta usada no pedido.

4. Reinicie o computador. 

Disable LAPS

 

Turn all items to disabled in LAPS GPO 

 

Remove LAPS passwords

Get-ADComputer -Filter * -SearchBase “OU=Servers,DC=mydomain,DC=com” | Set-ADComputer -clear ‘ms-mcs-AdmPwd’,‘ms-Mcs-AdmPwdExpirationTime’

 

Export password list

Get-ADComputer $computer -Properties ms-Mcs-AdmPwd | fT ms-Mcs-AdmPwd #Export-Csv -Path 'C:\Pwd.csv'

 

Backup / restore domain GPOs

Backup all GPOs 

Backup-Gpo -All -Path "\\Server1\GpoBackups"

Restore all GPOs
 

Restore-GPO -All -Domain "contoso.com" -Path "\\Server1\Backups"

Como verificar se os controladores de domínio estão sincronizados

 Etapa 1 - Verificar a integridade da replicação

Execute o comando abaixo:
Repadmin /replsummary

A operação "/replsummary" resume rapidamente o estado de replicação e a integridade relativa de uma floresta.


Etapa 2 – Verificar as solicitações de replicação de entrada que estão na fila.

Repadmin /Queue


Esse comando lista os elementos que permanecem na fila de replicação. Ele exibe solicitações de replicação de entrada que o controlador de domínio precisa emitir para se tornar consistente com seus parceiros de replicação de origem.

Etapa 3 - Verificar o status da replicação

Repadmin /Showrepl

Esse comando exibe o status de replicação quando o controlador de domínio especificado tentou pela última vez implementar uma replicação de entrada de partições do Active Directory. Ele ajuda a descobrir a topologia de replicação e a falha de replicação.

Etapa 4 – Sincronizar a replicação entre parceiros de replicação

Repadmin /syncall

Garante a sincronização entre parceiros de replicação
Etapa 5 – Forçar o KCC a recalcular a topologia

Repadmin /KCC

Este comando força o KCC (Knowledge Consistency Checker) nos controladores de domínio de destino a recalcular imediatamente sua topologia de replicação de entrada. Ele verifica e cria as conexões entre os controladores de domínio. Por padrão, o KCC é executado em segundo plano a cada 15 minutos para verificar se uma nova conexão foi estabelecida entre os controladores de domínio.

Etapa 6 – Forçar replicação

Repadmin /replicate

Este comando força a replicação da partição de diretório especificada para o controlador de domínio de destino do DC de origem.


Forçar sincronização:

Este é um  comando interessante caso haja algum problema com a replicação automática dos sites remotos do AD.
Ele força a replicação do AD primário para todos os sites.
O comando deve ser feito à partir do AD Primário. Na tela de Prompt do MS-Dos, entre com o comando abaixo:

repadmin /syncall /e /A /P /d /q

Aqui cada um dos parâmetros explicados:

/syncall: Sincroniza o domain controller principal com todos os parceiros de replicação;

/e: Enterprise… indica que a replicação será estendida a todos os sites remotos;

/A:  All; Sincroniza todas as partições do home server;

/P: Indica que as mudanças serão replicadas a partir do servidor primário;

/d: Identifica os servidores por seus nomes distintos em eventuais mensagens que possam aparecer;

/q: Quiet mode. Não mostra as mensagens de status. Caso você esteja fazendo isso manualmente por algum problema, é melhor não usar este parâmetro para identificar algum erro.








Powershell Active Directory Commands

Find Users or Computer which are expired

Use Search-AdAccount cmdlet to find user, computer or service account enable status

Search-ADAccount -AccountExpired


Check If Users password expired

Search-ADAccount -PasswordExpired


Check if Users account disabled

Search-ADAccount -AccountDisabled


Find all locked out account in active directory

Search-ADAccount -LockedOut | FT Name,ObjectClass -A


Find account inactive for last 90 days

Search-ADAccount -AccountInactive -TimeSpan 90.00:00:00 | FT Name,ObjectClass -A


Unlock User account

Unlock-ADaccount -identity "Garyw"


Get Ad User Distinguished Name

Get-AdUser -Identity "toms" | Select DistinguishedName


Get Ad User using userprincipalname

Use Get-AdUser cmdlet in Active directory to get user using provided userprincipalname.

Get-ADGroupmember -identity salesleader | % { get-aduser $_.samaccountname} | Select Name,UserPrincipalName


Get Ad User SID in active directory

Get-AdUser -Identity toms | Select Name, SID, UserPrincipalName


Modify property of Group in active directory

Lets consider an example to modify description property of group, run below command

Set-ADGroup -Server localhost:60000 -Identity "CN=AccessControl,DC=AppNC" -Description "Access Group" -Passthru

Above PowerShell script, uses Set-AdGroup to set description property using Description parameter.


List all active directory groups

PowerShell Get-AdGroup cmdlet get list of all active directory group, run below command

Get-ADGroup -filter * -properties * |select SAMAccountName, Description|


List of all users in AD group

PowerShell Get-AdGroupMember cmdlet gets active directory group members, run below command

Get-ADGroupMember -Identity "Shell_Sales" | Select-Object Name


Get all computers in Active Directory

PowerShell Get-AdComputer cmdlet get list of active directory computers.

Get-ADComputer -Filter *


Source: https://shellgeek.com


Set AdUser Home Directory in PowerShell

 Using the Set-AdUser cmdlet in PowerShell to set the home directory folder path.

Set-ADUser -Identity Arons -HomeDirectory 'D:\Arons'
 
Get-Aduser -Identity Arons -Properties * | Select SamAccountName,HomeDirectory,HomeDrive,ProfilePath

Entire OU set password never expires

 

dsquery user “OU={your target OU},DC={your domain},DC={your domain extension}” | dsmod user -pwdneverexpires yes

Update: Note: If your OU has more than 100 users in it you need to add the ‘-limit’ flag, and set it to a number greater than your actual amount of users, e.g.

dsquery user “OU={your target OU},DC={your domain},DC={your domain extension}” -limit 2000 | dsmod user -pwdneverexpires yes

 

Finding Stale User and Computer Accounts

Find Users Who Have Never Logged On

Use the following PowerShell Command;

Get-ADUser -Filter { LastLogonDate -notlike "*" -and Enabled -eq $true } -Properties LastLogonDate | Select-Object @{ Name="Username"; Expression={$_.SamAccountName} }, Name, LastLogonDate, DistinguishedName | Export-Csv C:\temp\Users-Never-Logged-On.csv

Note: This will output the users to a csv file, and requires you to have a C:\Temp directory.


Find Users Who Have Not Logged On In ‘x‘ Days

I’m going to use the value of 90 days (remember some staff might be on long term sick/maternity so check with HR!) Execute the following three commands;

$DaysInactive = 90
$TrueInactiveDate = (Get-Date).Adddays(-($DaysInactive))
Get-ADUser -Filter { LastLogonDate -lt $TrueInactiveDate -and Enabled -eq $true } -Properties LastLogonDate | Select-Object @{ Name="Username"; Expression={$_.SamAccountName} }, Name, LastLogonDate, DistinguishedName | Export-Csv C:\temp\Users-Inactive-90-days.csv


Note: This will output the users to a csv file, and requires you to have a C:\Temp directory.


Find Computers Who Have Not Logged On In ‘x‘ Days

Again I’m using 90 days.

$DaysInactive = 90
$TrueInactiveDate = (Get-Date).Adddays(-($DaysInactive))
Get-ADComputer -Filter { PasswordLastSet -lt $TrueInactiveDate} -properties PasswordLastSet | Select-Object Name, PasswordLastSet, DistinguishedName | Export-Csv C:\temp\Computers-Inactive-90-days.csv


Note: This will output the users to a csv file, and requires you to have a C:\Temp directory.

Add All Members of an OU to a Security Group

 

Get-ADUser -SearchBase ‘OU=Source-OU,OU=PNL,DC=pnl,DC=com’ -Filter * | 
ForEach-Object {Add-ADGroupMember -Identity ‘SG-Test-Group’ -Members $_ }

 

 

Getting Object Numbers From Active Directory

Users:
(Get-ADUser -Filter *).Count

Computers:
(Get-ADComputer -Filter *).Count

Groups:
(Get-ADGroup -Filter *).Count

Enabled or disabled users:
(Get-AdUser -filter 'Enabled -eq $true').count
(Get-AdUser -filter 'Enabled -eq $false').count


Group users:
(Get-ADGroup GS-VPN-Users -Properties *).Member.Count

OU users:
(Get-ADUser -Filter * -SearchBase "OU=Users, OU=PNL,DC=pnl,DC=com").Count

 

 

Simple Active Directory health test

Dcdiag.exe /v >> c:temppre_dcdiag.txt
This is a must and will always tell you if there is trouble with your DCs and/or services associated with it

Netdiag.exe /v >> c:temppre_Netdiag.txt
This will let me know if there are issues with the networking components on the DC.  This along with the post test also is a quick easy way to ensure the patch I just installed is really installed (just check the top of the log)

Netsh dhcp show server >> c:temppre_dhcp.txt
Some may not do this but I”ve felt the pain of a DHCP server somehow not being authorized after a patch.  This allows me verify the server count and names.

Repadmin /showreps >> c:temppre_rep_partners.txt
This shows all my replication and if it was successful or not.  Just be aware that Global Catalogs will have more info here than a normal domain controller.

repadmin /replsum /errorsonly >> c:temppre_repadmin_err.txt
This is the one that always takes forever but will let you know who you are having issues replicating with.


Domain controller verbose mode

Put the domain controller in verbose logging for the netlogon service to actually find out where the logon attempt was coming from. First, open up command prompt as an administrator and execute the following command:
nltest /dbflag:0x2080ffff

Once done, execute the following command to turn off the debugging:
nltest /dbflag:0x0

This logs every transaction made to the file: %windir%\debug\netlogon.log (note, you need to run notepad as an administrator to read this file).


source: https://support.microsoft.com/en-us/help/109626/enabling-debug-logging-for-the-netlogon-service



Moving users to OU - powershell


 
# Specify target OU. This is where users will be moved.
$TargetOU =  "OU=Districts,OU=IT,DC=enterprise,DC=com"
# Specify CSV path. Import CSV file and assign it to a variable. 
$Imported_csv = Import-Csv -Path "C:\temp\MoveList.csv" 

$Imported_csv | ForEach-Object {
     # Retrieve DN of user.
     $UserDN  = (Get-ADUser -Identity $_.Name).distinguishedName
     # Move user to target OU.
     Move-ADObject  -Identity $UserDN  -TargetPath $TargetOU
   
 }

Enabling / Disabling single and multiple user accounts


Disabling a single user account can be done by executing below one-liner PowerShell commands:

Disable-ADAccount –Identity “TestAccount”

or

Disable -ADAccount –Identity “CN=TestAccount,OU=Users,DC=example,DC=Com”


Disabling - bulk


$UserAccounts = "C:\Temp\Users.txt"
Foreach ($ThisUser in Get-Content "$UserAccounts")
{
Disable-ADAccount -Identity $ThisUser
}




To enable, just change Disable-ADAccount by Enable-ADAccount


Checking who rebooted a production server


One of the production servers got rebooted unexpectedly and you would like to find out who rebooted it and when the server got rebooted. In PowerShell, you can take a look at the event log using the PowerShell one-liner command shown below. You don’t need to write a bunch of lines in a script and then run the script. Here is how you do it.

Get-EventLog –Log System –Newest 100 | Where-Object {$_.EventID –eq ‘1074’} | FT MachineName, UserName, TimeGenerated -AutoSize

The above command checks the System event log and searches for Event ID 1074 and then prints the machine name, username, and time the event got generated. If you would like to save the output to a CSV file, simply use Export-CSV cmdlet as shown in the command below:

Get-EventLog –Log System –Newest 100 | Where-Object {$_.EventID –eq ‘1074’} | FT MachineName, UserName, TimeGenerated –AutoSize | Export-CSV C:\Temp\AllEvents.CSV -NoTypeInfo






Back up all production Group Policy Objects

If you would like to backup all production Group Policy Objects (GPOs) in an Active Directory environment, use Backup-GPO PowerShell cmdlet as it is highlighted in the command below:

Backup-GPO –All –Path C:\Temp\AllGPO

List Windows AD active users



Get-ADUser -LDAPFilter "(&(sAMAccountName=*)(!userAccountControl:1.2.840.113556.1.4.803:=2))" ` -Properties sAMAccountName, givenName, sn, mail, enabled | Select sAMAccountName, givenName, sn, mail, enabled | ` Export-Csv -Path c:\Users.csv -NoTypeInformation


GPO error with samba 4

GPO from samba 4 don't work.

On server:  
samba-tool ntacl sysvolreset

On windows client: 
gpupdate /force




NTFRS - journal wrap errors detected on domain controller


File Replication Service has detected that the replica set “DOMAIN SYSTEM VOLUME (SYSVOL SHARE)” is in JRNL_WRAP_ERROR

Are you getting this error in your File Replication Service?

The File Replication Service has detected that the replica set “DOMAIN SYSTEM VOLUME (SYSVOL SHARE)” is in JRNL_WRAP_ERROR.
Replica set name is : “DOMAIN SYSTEM VOLUME (SYSVOL SHARE)”
Replica root path is : “c:\windows\sysvol\domain”
Replica root volume is : \\.\C:
A Replica set hits JRNL_WRAP_ERROR when the record that it is trying to read from the NTFS USN journal is not found. This can occur because of one of the following reasons.
[1] Volume “\\.\C:” has been formatted.
[2] The NTFS USN journal on volume “\\.\C:” has been deleted.
[3] The NTFS USN journal on volume “\\.\C:” has been truncated. Chkdsk can truncate the journal if it finds corrupt entries at the end of the journal.
[4] File Replication Service was not running on this computer for a long time.
[5] File Replication Service could not keep up with the rate of Disk IO activity on \\.\C:.
Setting the “Enable Journal Wrap Automatic Restore” registry parameter to 1 will cause the following recovery steps to be taken to automatically recover from this error state.

This is caused when the Sysvol gets currupted and is simple to fix. I will walk you through the steps.

First off before we do anything lets backup by taking a Shadow Copy of the C: Drive. To do this we will open MyComputer and select the C:Drive, right click it and select properties. Now find the ShadowCopy Tab, highlight the C: Drive and click the “Create Now” button to create a backup point on the drive. You do not need to “Enable” ShadowCopy to take a 1 time snapshot.

Now that we have a backup point to go to if all hell breaks loose we can safely move on to the next step.
Open up  REGEDIT and navigate to the RegKey -> System\CurrentControlSet\Services\NtFrs\Parameters and create a new REG_DWORD key called Enable Journal Wrap Automatic Restore and place a 1 as the hex value.

Now launch a Command window(DOS) and run the following commands:

    NET STOP NTFRS

    NET START NTFRS

This will then cause the following to appear in your File Replication Service Event Log:

The File Replication Service is deleting this computer from the replica set “DOMAIN SYSTEM VOLUME (SYSVOL SHARE)” as an attempt to recover from the error state,
Error status = FrsErrorSuccess
At the next poll, which will occur in 5 minutes, this computer will be re-added to the replica set. The re-addition will trigger a full tree sync for the replica set.

This will be followed by the following Event Log:

File Replication Service is scanning the data in the system volume. Computer MyDomainServer cannot become a domain controller until this process is complete. The system volume will then be shared as SYSVOL.

This will be followed by the following Event Log:

The File Replication Service moved the preexisting files in
c:\windows\sysvol\domain to c:\windows\sysvol\domain\NtFrs_PreExisting___See_EventLog.

Now we need to wait a bit and allow the replication to complete. This has taken anywhere from 5 minutes to 20 minutes for me based on server and what is being replicated. You will know it is complete when you get the Event Log:

The File Replication Service is no longer preventing the computer MyDomainController from becoming a domain controller. The system volume has been successfully initialized and the Netlogon service has been notified that the system volume is now ready to be shared as SYSVOL.

Once you get this log your replication is complete and the Journal Wrap issues are fixed. We now need to go back to REGEDIT and change the entry we placed in there from a 1 to a 0.

Apt only upgrade selected packages

 apt list --upgradable | cut -d"/" -f1 > /tmp/apt pico /tmp/apt cat /tmp/apt | tr "\n" " " apt install --on...

Mais vistos