Tag Archives: AD Management

Account locked Out Randomly

A user was reporting that at random his AD Account was locked. He ensured me that he did not type his password wrong. After the first six reset I did not believe him. The user was an Administrator so I asked him if by any chance he installed any service under his name. He did change his password some time ago. We decided to revert to his old password. However the problem still occurred. I looked further into the problem. First searching why his account was locked out. On the first domain controller I ran a command:

Get-EventLog -LogName Security | ?{$_.entrytype -eq "FailureAudit" -and $_.message -match "SAMACCOUNTNAMEOFUSER"}

Change the SAMACCOUNTNAMEOFUSER to the sAMAccountname of the user. Add | FL for a larger output of the error.

This retured a set of four result. Three where at the exact same time one was some time after. The message was Kerberos Authentication Failed. The last time was the time that the user came to me saying his account was locked out again.

At the client address was an IP-address specified. It seemed that the Admin had an inactive session on that server or an scheduled task of some sort. Maybe even a service under his account.

I could not enter a pssession to that specific server. So I used a good old DOS Command:

query user /server:IPOFTHATSERVER

It retured the following output:

OutputQueryUser

This  session was logged on far before he changed his password. Maybe this account tried to log on to the domain with an old ticked which caused the DC to lock his account. Maybe he had an open file which occasionally tried to save with old credentials. It did however solve the problem

Random Password Generator

Generates strong passwords

PS1:

$length = 9
For ($a=48;$a –le 122;$a++) {$ascii+=,[char][byte]$a }
Function GET-Temppassword() {

Param(

[int]$length=10,

[string[]]$sourcedata

)

For ($loop=1; $loop –le $length; $loop++) {

            $TempPassword+=($sourcedata | GET-RANDOM)

            }

return $TempPassword

}

For ($a=48;$a –le 122;$a++) {$ascii+=,[char][byte]$a }

GET-Temppassword –length $Length –sourcedata $ascii

Optional Function:

Function GET-Temppassword() {

Param(

[int]$length=10,

[string[]]$sourcedata

)

For ($loop=1; $loop –le $length; $loop++) {

            $TempPassword+=($sourcedata | GET-RANDOM)

            }

return $TempPassword

}

ZIP:

 

Setting User logon hours

To set the user logon hours to 24×7 run the following script:

PS1:

Import-Module ActiveDirectory
$gebruikerslijst = Get-aduser -Filter * -Properties DistinguishedName

Foreach ($gebruiker in $gebruikerslijst){
$user = [ADSI]"LDAP://$gebruiker"
[byte[]]$hours = @(255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255)
$user.logonhours.value = $hours
$user.setinfo() 
}

Each byte represents 8 hours. The first byte start at 1 am at sunday untill 9 am at sunday. This next is byte is from 9 am untill 17 pm at sunday and so forth. Each byte represents of course 8 bit. Each bit is an hour. So to deny access on the first hour one should use 254.

ZIP:

Logonhours

Empty ADGroup

Script reads old group name and new group name from CSV file.  The processes data from XML and PS1 file. It exports the previous rights to a CSV file in the subdir CSVfiles. Needs XML and CSV files.

PS1:

$xmlConfigfile = ".EmptyADgroup.xml"

	While (((Test-Path $xmlConfigfile) -eq $false) -or ($NoXML)){
		[System.Windows.Forms.MessageBox]::Show("ERROR: $xmlConfigfile not found!")
	write-host De XML file kan niet gevonden worden -F Red
	If (!($psISE)){"Press any key to continue...";[void][System.Console]::ReadKey($true)}
	exit
	}

	If (-not ($CSV -and $Header -and $Migrated -and $Domain -and $OUlocal1 - $OUlocal2 -and $OUGlobal1 -and $OUGlobal2)) {
		$xml = get-content $xmlConfigfile
		If (-not $CSV) {$CSV = $xml.Config.Settings.CSV}
		If (-not $Header) {$Header = $xml.Config.Settings.Header}
		If (-not $Migrated) {$Migrated = $xml.Config.Settings.Migrated}
		}

Import-Module ActiveDirectory

		While (((Test-Path $CSV) -eq $false) -or ($NoCSV)){
		[System.Windows.Forms.MessageBox]::Show("ERROR: $xmlConfigfile not found!")
	write-host De CSV file kan niet gevonden worden -F Red
	If (!($psISE)){"Press any key to continue...";[void][System.Console]::ReadKey($true)}
	exit
	}

$list = @(import-csv -Delimiter ';' $CSV)
write-host ".CSV file contains" $list.count " lines." -F Yellow -B DarkCyan
$list[0]

if ($error.count -ne 0)

{
	write-host "An error occurred during the operation. Details follow:"
	$error[0].categoryInfo
	$error[0].invocationinfo
	write-host "=========================================================="
	write-host "Quit due to an error" -Fore Red
	Exit
}
else
{
	#"Successfully opened .CSV file..."
}

#Loop through .CSV file
foreach($entry in $list)

{
	# Reset the variable to make sure that they are clean before processing a user.
	$Oldgroup=$entry.OldGroup
	$NewGroup=$entry.NewGroup

	if ($Oldgroup -ne $null){$CSVExportFile = ($Oldgroup+".csv")}

		While (((Test-Path ".CSVFiles$CSVExportFile") -ne $false) -or ($NoCSVExportFile)){
		[System.Windows.Forms.MessageBox]::Show("ERROR: $CSVExportFile already exists!")
	write-host Het CSV bestande $CSVExportFile bestaat al -F Red
	If (!($psISE)){"Press any key to continue...";[void][System.Console]::ReadKey($true)}
	exit
	}
	write-host "Er wordt een export gemaakt van de groep $Oldgroup" -b DarkCyan -f Yellow
	$lijst = get-adgroupmember	 $Oldgroup -recursive

	Add-content -Value $Header -Path ".CSVFiles$CSVExportFile"

	foreach ($item in $lijst){
	$Outinfo = $Oldgroup + ";" + $item.samaccountname
	Add-content -Value $Outinfo -Path ".CSVFiles$CSVExportFile"}

			While (((Test-Path ".CSVFiles$CSVExportFile") -eq $false) -or ($NoCSVExportFile)){
		[System.Windows.Forms.MessageBox]::Show("ERROR: $CSVExportFile not found!")
	write-host Het CSV bestand $CSVExportFile is niet weggeschreven -F Red
	If (!($psISE)){"Press any key to continue...";[void][System.Console]::ReadKey($true)}
	exit
	}
	write-host "De export is gemaakt van de groep $Oldgroup op locatie .CSVFiles$CSVExportFile" -b DarkCyan -f Yellow
	write-host "De users in de groep $Oldgroup worden nu uit de groep gehaald" -b DarkCyan -f Yellow
	foreach ($item in $lijst){

	Remove-ADGroupMember $oldgroup -Members $item.samaccountname -Confirm:$false
	}

	$lijst = get-adgroupmember $Oldgroup -recursive
	if ($lijst -ne $null) {write-host "Niet alle users zijn uit de groep $oldgroup gehaald" -b Black -f Red}
	if ($lijst -eq $null) {write-host "Alle users zijn uit de groep $oldgroup gehaald" -b DarkCyan -f Yellow}
	if ($lijst -eq $null) {$Description = get-adgroup "ALC_APL_mibores" -Properties * | ForEach-Object {$_.Description}}
	$AddDescription = "$Migrated $Newgroup |"
	$Description = [string]$description
	$Description = ($AddDescription+$description)
	if ($lijst -eq $null) {Set-ADGroup $Oldgroup -Description $Description}

	}

XML:

<Config> 
  <Settings>
	<CSV>.EmptyADgroup.csv</CSV>
	<Header>Group;sAMaccountname</Header>
	<Migrated>Deze Groep is gemigreerd naar de groep</Migrated>
  </Settings>
</Config>

CSV:

Oldgroup;Newgroup
Oldgroup;Newgroup

ZIP:

EmptyADgroup

 

Get Inherited Permission

Script reads DFS Location from host. Script reads ADuser from host. Script checks whether DFS location and User specified are correct. Then checks how the user have access to the folder and what NTFS rights the user has.

PS1:

#Load Active Directory modules
Import-Module ActiveDirectory 
Clear-host
$Locatie = Read-Host "Voer de DFS Locatie in in UNC Format bijvoorbeeld:\gemeentenet.localdfsdeelnemerfolder"
While ((Test-Path $Locatie) -ne $true){
write-host "De opgegeven locatie bestaat niet. Voor opnieuw in" -b Black -f Red
$Locatie = Read-Host "Voer de DFS Locatie in in UNC Format bijvoorbeeld:\gemeentenet.localdfsdeelnemerfolder"
While ((Test-Path $Locatie) -ne $true){
	[System.Windows.Forms.MessageBox]::Show("ERROR: $locatie bestaat niet. Het script is beeindigd!")
	write-host De $locatie bestaat niet. Voer het script opnieuw uit! -F Red
	If (!($psISE)){"Press any key to continue...";[void][System.Console]::ReadKey($true)}}}
$User = Read-Host "Voer de User in in sAMaccountname Format bijvoorbeeld:othsbe02"
$testresult = get-aduser $User
If ($testresult -eq $null){
write-host "De opgegeven User bestaat niet. Voor opnieuw in" -b Black -f Red
$User = Read-Host "Voer de User in in sAMaccountname Format bijvoorbeeld:othsbe02"
$testresult = get-aduser $User
if ($testresult -eq $null){
	[System.Windows.Forms.MessageBox]::Show("ERROR: $User bestaat niet. Het script is beëindigd!")
	write-host De $User bestaat niet. Voer het script opnieuw uit! -F Red
	If (!($psISE)){"Press any key to continue...";[void][System.Console]::ReadKey($true)}}}
$Folders = @()
$Folders = get-item $locatie  | where {$_.psiscontainer -eq $true}
$outfile = ".temp.csv"
$Header = "Folder Path;IdentityReference;AccessControlType;IsInherited;InheritanceFlags;PropagationFlags;Filesystemrights"
Add-Content -Value $Header -Path $OutFile 
foreach ($Folder in $Folders){
	$ACLs = get-acl $Folder.fullname | ForEach-Object { $_.Access  }
	Foreach ($ACL in $ACLs){
	$OutInfo = $Folder.Fullname + ";" + $ACL.IdentityReference  + ";" + $ACL.AccessControlType + ";" + $ACL.IsInherited + ";" + $ACL.InheritanceFlags + ";" + $ACL.PropagationFlags + ";" + $ACL.FileSystemRights
	Add-Content -Value $OutInfo -Path $OutFile	
	}}

	$CSVImport = import-csv $outfile -delimiter ";"	
	$list1 = @()
	foreach ($item in $CSVImport){
	$identity = $item.Identityreference.replace("GEMEENTENET","")
	if ($item -match "BUILTIN" -and $item -match "Users"){$identity = $item.Identityreference
	$temp1 = Get-ADGroupmember -identity "Domain Users" -recursive |ForEach-Object {$_.sAMaccountname}}

	if ($item -notmatch "Builtin" -and $item -notmatch "NT AUTHORITY" -and $item -notmatch "CREATOR"){
	$temp1 = Get-ADGroupmember $identity -recursive |ForEach-Object {$_.sAMaccountname} }

	if ($item -match "BUILTINAdministrators"){$identity = $item.Identityreference.replace("BUILTIN","")
	$temp1 = Get-ADGroupmember $identity -recursive |ForEach-Object {$_.sAMaccountname} }
	foreach ($line in $temp1){$list1 += $line + ";" + $identity + ";" + $item.FileSystemRights}
	$result = $list1 |? {$user -contains $_}}

$print = $list1 -match $user
$print | sort -unique
remove-item $outfile

ZIP:

 

Volgnummer bijhouden in een CSV file

Import-module 'ActiveDirectory'
 $getadusers = @()
 $filter = @()
 $samaccountnamelijst = @()
 $Header = 'Samaccountname'
 $CSV = '.\Gemeentenet.csv'
 $Extension = $null
 $import = @()
 Add-Content -Value $Header -Path $CSV
 $getadusers = Get-aduser -filter *
 foreach ($entry in $getadusers){if ($entry -ne $null){$samaccountnamelijst += $entry.samaccountname}}
 foreach ($sam in $samaccountnamelijst){Add-Content -Value $sam -Path $CSV}
 $Deelnemerlijst = @()
 $allusers = import-csv $csv
 foreach ($Deelnemeruser in $allusers){if ($Deelnemeruser -match $deelnemer){$Deelnemerlijst += $Deelnemeruser}}
 $Deelnemerlijst | export-csv .\$Deelnemer.csv

$entry = $null
$username = 'othext'
 $CSV = '.\Gemeentenet.csv'
 $import = @()
 $filter = @()
 $import = import-csv $csv
 foreach ($entry in $import){if ($entry -match $username){$filter += $entry.samaccountname}}
 $filter = $filter -split "@{samaccountname=" |sort
 $filter = $filter -split "$username" | sort
 $filter = $filter -split "}" | Sort -Descending
 $nummer = [int]$filter[0]
 $nummer++

Add-content -Value $volledigesamaccountname -path $csv

Custom query voor users met

Het is mogelijk om Active Directory Users and Computers (dsa.msc) een custom query te doen. In de situatie dat je een groep gebruikers hebt aangemaakt en deze weer moet verwijderen of moet toevoegen aan een groep. Voor de situatie dat je wil weten welke users zijn aangemaakt na 27 oktober 2013 voer je volgend commando in:

 

(objectCategory=user)(whenCreated>=20131027000000.0Z)