Friday 27 November 2020

Create Group which correspond to Server Name

 # This script create Group which correspond to Server Name. 

# Import Active Directory Module.

Import-Module ActiveDirectory

# Computer OU Container

$ParentOU="OU=Root,DC=test,DC=local"

# Locate the Group OU, in which script will create groups.

$GroupOU="OU=ServerGroup,OU=Root,DC=test,DC=local"

# The script will find computer object which is leass than specified in the customdate

$customdate=(Get-date).Adddays(-3)

$log=get-date

$ColComputers=get-adComputer -SearchBase $ParentOU -Filter {(Whencreated -ge $customdate)}

foreach ($Computer in $ColComputers)

{

$ComputerCN = (Get-ADComputer $Computer).name

# Verify the OU path before group creation process

$check = [ADSI]::Exists("LDAP://$($GroupOU)") 

if ($check -eq $True)

Try 

# Check Group Already exist in Directory Service

$GroupExists = Get-ADGroup -Identity $ComputerCN

# If Group Already exist, redirect the output to log file.

$Outmsg="Group $($ComputerCN) alread exists! Group creation skipped!$log" 

$Outmsg | Out-file -append ".\Result_Log1.txt"

}

Catch

{

# IF Group not exist in AD, create new group which is correspond to computername

$create = New-ADGroup -Name $ComputerCN -GroupScope: "Global" -Path: "$GroupOU" -SamAccountName:"$ComputerCN" -Description "Local Administrator Group for $ComputerCN"  -Server:"NATEST-DC1" 

$Outmsg= "Group $($ComputerCN) created!$log" 

$Outmsg | Out-file -append ".\Result_Log1.txt"

 

 } 

  } 

  Else 

  { 

    Write-Host "Target OU can't be found! Group creation skipped!" 

  } 

}

Thursday 19 November 2020

Active Directory Replication Report

 # Get today's date for the report 

$today = Get-Date 

 

# Setup email parameters 

$subject = "Replication REPORT - " + $today 

$priority = "Normal" 

$smtpServer = "SMTP.Server.com" 

$emailFrom = "from@email.com" 

$emailTo = "to@email.com" 

$log = "C:\temp\ReplicationSummary.txt"

repadmin /replsum * /bysrc /bydest /sort:delta > $log

#$ReplicationStatus = "Replication REPORT - " + $today 


$Result = Get-Content C:\temp\ReplicationSummary.txt -raw


# Send the report email 

Send-MailMessage -To $emailTo -Subject $subject -Body $Result -SmtpServer $smtpServer -From $emailFrom -Priority $priority

Saturday 20 June 2020

Update Missing Group Owner Attribute in MIM

[cmdletbinding()]           
param()
Set-ResourceManagementClient -BaseAddress “http://TEST-MIM.test.com:5725”
$MIMGroups = Get-Content C:\Temp\ADGroups.txt
foreach ($MIMGroup in $MIMGroups) {
$og = get-resource -ObjectType "Group" -AttributeName "AccountName" -AttributeValue "$MIMGroup"
$owner = $og.Owner | Select-Object -ExpandProperty value -First 1
$og.DisplayedOwner = "$owner"
Save-Resource $og
}

Microsoft Identity Manager Group Report

 # Microsoft Identity Manager Group Report

[cmdletbinding()]           
param()

# Connect MIM Identity Manager

Set-ResourceManagementClient -BaseAddress “http://Mim.test.com:5725”

# List of AD Groups from specific OU.

$MIMGroups = Get-ADGroup -Filter * -SearchBase "OU=Test-MIM,DC=Test,DC=com" -Properties * | Select-Object -ExpandProperty SamAccountName

# Check each Group Attribute one at time

foreach ($MIMGroup in $MIMGroups) {

# Check Group Attribute from Metaverse and store value into Variable

$og = get-resource -ObjectType "Group" -AttributeName "AccountName" -AttributeValue "$MIMGroup"

# Create Powershell Object and extract specific attribute from Og variable

 $obj = New-Object -Type PSObject -Property (           
  @{           
   "AccountName"  = $og.AccountName;           
   "DisplayName" = $og.DisplayName;
   "AuthoritativeDirectory" = $og.AuthoritativeDirectory;           
   "DisplayedOwner" = $og.DisplayedOwner;
   "Owner" = $og.Owner
  }           
 )

# Export values into excel
         
 $Obj |Select-Object AccountName,DisplayName,AuthoritativeDirectory,@{Name="DisplayedOwner";e={$_.DisplayedOwner -join ","}},@{Name="Owner";e={$_.Owner -join ","}} | export-csv c:\temp\AllADGroups.csv -notypeinformation -Encoding UTF8 -Append       
}

Wednesday 22 April 2020

Check SPN Entry Contains DNS Alias

# DNS Alias Info

$DNSAlias = Get-Content C:\temp\nas.txt

# AD Server Information

$ADObjects = Get-ADComputer -Filter * -SearchBase "OU=TESTServer,DC=test,DC=local" -Property Name,ServicePrincipalName | Select-Object name,@{Name="SPN";e={$_.ServicePrincipalName -join ","}}

# Check Server SPN entry contains DNS Alias

foreach ($DNS in $DNSAlias){
foreach ($ADObj in $ADObjects){
    If ($ADObj -like "*$DNS*"){
        $log = "$DNS Object found in $ADObj" | Out-File -Append C:\temp\Result.txt
    }else{
        $Log = "$Dns Object Not Found in $ADObj" | Out-File -Append C:\temp\Result-Not.txt
    }
    }
    }

Check Active Directory Computer Object Contains DNS Alias

# DNS Alias Info

$DNSAlias = Get-Content C:\temp\dns.txt

# AD Server Information

$ADObjects = Get-Content C:\temp\nas.txt| Get-ADComputer -Property
Name,ServicePrincipalName | Select-Object name,@{Name="SPN";e={$_.ServicePrincipalName -join ","}}

# Check Server SPN entry contains DNS Alias
foreach ($DNS in $DNSAlias){
foreach ($ADObj in $ADObjects){
    If ($ADObj -like "*$DNS*"){
        $log = "$DNS Object found in $ADObj" | Out-File -Append C:\temp\Result.txt
    }else{
        $Log = "$Dns" | Out-File -Append C:\temp\Result-Not.txt
    }
    }
    }

Check OS Information List of Computers


$dcs = Get-Content C:\temp\server.txt

foreach ($dc in $dcs){

    If ((Get-ADComputer -Filter 'Name -like $dc') -ne $null)
    {
    Get-ADComputer -Identity $dc -Properties * | Select-Object name,OperatingSystem | Export-Csv C:\temp\3.csv -Append -NoTypeInformation

    }

    else {
    "$DC" |Select-Object @{name="Name";e={$Dc}},OperatingSystem | Export-Csv C:\temp\3.csv -Append -NoTypeInformation
    }
    } 

Check SMB feature Installed on Domain Controllers

$DCs = Get-ADDomainController -Filter * | Select-Object name -ExpandProperty name

    foreach ($dc in $dcs ) {
    Get-WindowsFeature -computername $dc fs-smb1 | Select-Object @{name="Computer Name";e={$Dc}},InstallState

    }  

Check Specific REG Value IN All Domain Controllers


$DCs = Get-ADDomainController -Filter * | Select-Object name -ExpandProperty Name

foreach ($dc in $dcs){

Invoke-Command -ComputerName $dc -ScriptBlock {Get-ItemProperty -Path HKLM:\System\CurrentControlSet\Services\ntds\Diagnostics\ | select @{Name="Server Name";e={$dc}},"16 LDAP Interface Events"}

}

Event log Count in Domain Controller


#List of Domain Controller to pull the events and get the count

$DCs = Get-ADDomainController -Filter * | Select-Object -ExpandProperty Name

foreach ($dc in $dcs){

    $log = (Get-EventLog -LogName 'Directory Service' -ComputerName $dc | Where-Object {$_.EventID -eq '4770'}).count

    Write-Host "Name of $DC No of event in count $log"

    } 

Extract The Group Members from Custom Groups


# Custom Group List

$ServerNameGroup = Get-Content C:\temp\Server.txt

# Extract Group Members one by one.

foreach ($ADGroup in $ServerNameGroup){

    # Check If Group Already have member to extract

    If ((Get-ADGroupMember $ADGroup ).length -ne 0){
    Get-ADGroupMember -Identity $ADGroup | select @{Name="ServerNameGroups";expression={$ADGroup}},name,objectClass  |Out-File -Append C:\temp\Gropinfo.csv
    } Else {

    # Add Empty Group in Log.

    "$ADGroup Member Value is Empty" |Out-File -Append C:\temp\Gropinfo.csv

    }
    } 

Thursday 12 March 2020

Password Expire Email Notification

The below script would help us to send an email notification, when user password expires on specific group members. 




Remove-Item C:\temp\Password.html -Force

$Domainname = (Get-ADDomain).Name

$PasswordPolicy = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge.days

$Today = (Get-Date).AddDays($PasswordPolicy)

$Users = Get-ADGroupMember -Identity "GroupName" | Get-ADUser | Where-Object {$_.Enabled -eq $true} |Select-Object -ExpandProperty SamAccountName

$CustomDay = 10

foreach ($User in $users) {

   $Pass = ((Get-ADUser -Identity $User -Properties * | Select-Object -ExpandProperty passwordlastset) - $Today).Days

    If ($pass -ge $CustomDay) {
   
        Get-Aduser -Identity $User -Properties * | Select-Object SamAccountName,passwordlastset,@{Name="PasswordExpiredON";e={$Pass}} | ConvertTo-Html | Out-File -Append "C:\Temp\Password.html"
   
    } elseif ($pass -le $CustomDay){

        Get-Aduser -Identity $User -Properties * | Select-Object SamAccountName,passwordlastset,@{Name="PasswordAlredyExpired";e={$Pass}} | ConvertTo-Html | Out-File -Append "C:\Temp\Password.html"
   
       
    }
    else {
        Out-File "All User Look Good" | ConvertTo-Html | Out-File -Append "C:\Temp\Password.html"

    }
    }


$Result = Get-Content C:\temp\password.html -Raw

# Creating Email Variable

$subject = "Password Expire Notification for the Domain" + $domainname
$priority = "Normal"
$smtpServer = "mail.test.com"
$emailFrom = "email@test.com"
$emailTo = "email@test.com"

# Sedning Report

Send-MailMessage -To $emailTo -Subject $subject -Body $Result -BodyAsHtml -SmtpServer $smtpServer -From $emailFrom -Priority $priority


Tuesday 4 February 2020

Monitoring Server Certificate and Send email to owner when it about to expire


# Get today's date for the report

$Date = Get-Date

# Taking Server Name

$ServerName = $env:Computername

# Checking the Certificate expire infomration and storing as HTML in C:\temp\report.html

Get-ChildItem -Path cert:\localmachine\My | Where-Object {$_.NotAfter -lt ($date).AddDays(30)} | Select-Object @{Name="ComputerName";e={$Servername}},Subject,Issuer,DnsNameList,@{Name="Cert Expires ON";e={$_.NotAfter}},NotBefore,EnhancedKeyUsageList | ConvertTo-Html | Out-File C:\temp\Report.html


# Taking html report as variable

$Result = Get-Content C:\temp\Report.html -Raw

# Creating Email Variable

$subject = "$ServerName Certification Expires Report- " + $Date
$priority = "Normal"
$smtpServer = "Mail.Google.com"
$emailFrom = "Xyz.com"
$emailTo = "abc.com"

# Sedning Report

Send-MailMessage -To $emailTo -Subject $subject -Body $Result -BodyAsHtml -SmtpServer $smtpServer -From $emailFrom -Priority $priority

Wednesday 29 January 2020

Bulk DNS Record Deletion

# Update List of HOSTNAME in host.txt file

$DNSDATAs = Get-Content .\host.txt

foreach ($dns in $DNSDATAs){

# If DNS Record exist, If block will process

If ((Get-DnsServerResourceRecord -ZoneName lab.local $dns -ErrorAction SilentlyContinue).hostname -ne $null) {
    Remove-DnsServerResourceRecord -ZoneName lab.local -RRType "A" -Name $dns -Force
    $Result = "$dns Record deleted successfully"| Out-File -Append ".\dnslog.log"

# If DNS Record not found else block will process

} else {
    $Result = "$dns Record NOT found in Zone" | Out-File -Append ".\dnslog.log"
}
}

Extract AD Group Member Info




# Name Of the Groups, where we need to pull the Group information.

$GroupNames = Get-Content C:\temp\Server.txt

# Check each group once at time.

    foreach ($ADGroup in $GroupNames){

    # Check If Group having Members, if Group contains members will process the If block.

    If ((Get-ADGroupMember $ADGroup ).length -ne 0){

    Get-ADGroupMember -Identity $ADGroup | select @{Name="GroupName";expression={$ADGroup}},name,objectClass  |Out-File -Append C:\temp\Gropinfo.csv

    }

    Else {

    # If Group is empty, else block will process.

    "$ADGroup Member Value is Empty" |Out-File -Append C:\temp\Gropinfo.csv

}
}  

Tuesday 28 January 2020

Compare Active Directory Group Members from One User To Other User

# Reference User

$Refernceuser = Get-ADUser -Identity User1 -Properties * | Select-Object MemberOf -ExpandProperty Memberof | Get-ADGroup -Properties * | Select-Object -ExpandProperty Name

# User Who need similar access to Refernce User

$User = Get-ADUser -Identity User2 -Properties * | Select-Object MemberOf -ExpandProperty Memberof | Get-ADGroup -Properties * | Select-Object -ExpandProperty Name

# Compare Group MemberInfo

Compare-Object -ReferenceObject $Refernceuser -DifferenceObject $User | Where-Object {$_.SideIndicator -eq "<=" -and $_.Inputobject -like "*Grou*"}

Check Server Group Info and Add Object To AD Group V1

          Many Scenario we push GPO, based on Server Group Member Info. The below Scrips will help us to Add Servers into Specific ADGroup. 

# Specify list of OU followed by Comma Separator.
$OUs = "OU=DomainServer,OU=DomainObjects,DC=lab,DC=local","OU=DomainAdmin,OU=DomainObjects,DC=lab,DC=local"

# Active Directory Group
$ADGroup = "CN=GroupA,OU=DomainGroup,OU=DomainObjects,DC=lab,DC=local"

# Check each OU One at time
foreach ($OU in $OUs){

# Store All Servers in each OU
$Servers = Get-Adcomputer -Filter * -SearchBase $OU

# Check each Server in Specifiy OU
foreach ($Server in $Servers){

# Collecting Server Group Memberof Information
$ServerGroupInfo = Get-ADComputer -Identity $Server -Properties * | Select-Object MemberOF -ExpandProperty MemberOF

# Check if Server is Memberof  AD Group
If($ServerGroupInfo -contains $ADGroup){

# IF Server is MemberOf ADGroup, update Log
$Log =  "$Server is MemberOF $ADGroup" |Out-File -Append ".\Report.log"
}else{
# If Server not Memberof ADGroup, Add Server object into ADGroup

Add-ADPrincipalGroupMembership -Identity $Server -MemberOf $ADGroup
# Finally Update log
$Log = "$Server is Added to $ADGroup" | Out-File -Append ".\Report.log"
}
}

}

Check Server Group Info and Add Object To AD Group

            Many Scenario we push GPO, based on Server Group Member Info. The below Scrips will help us to Add Servers into Specific ADGroup. 

# Name of The OU, where we are going to take Input Object

$OU = "OU=DomainServer,OU=DomainObjects,DC=lab,DC=local"

# Active Directory Group,

$ADGroup = "CN=GroupA,OU=DomainGroup,OU=DomainObjects,DC=lab,DC=local"

# Get Server Information

$Servers = Get-ADComputer -Filter * -SearchBase $OU

# Check each Servers if they are part of GroupA.

foreach ($Srv in $Servers){

# Checking Server Group information

   $ServerGroupMemberof = Get-ADComputer -Identity $Srv -Properties * | Select-Object MemberOf -ExpandProperty MemberOf

# Check If Server Memberof contains ADGroup

If ($ServerGroupMemberof -contains $ADGroup){

# If Server MemberShip Contains AD Group Log the Result.

$Log= "Server $Srv MembeorOf $ADGroup" |out-file -Append ".\Result.txt"

}
# IF server does not have Group Member info, it will add Group.
else {

# Adding Servers into Group

Add-ADPrincipalGroupMembership -Identity $Srv -MemberOf $ADGroup

# Storing the result in logs.
$Log = "Server $Srv Has benn MemberOF $ADGroup"|Out-File -Append ".\Result.txt"
}
}

Simple Script To Check, if Client using Correct TimeSource

# Collecting All Active Directory server Information

$ADServers = (Get-ADForest).Domains | %{ Get-ADDomainController -Filter * -Server $_ } | Select-Object name -ExpandProperty name

# Checking Local time Source from Client Computer

$Windowstime = w32tm /query /source

# Took Only hostname from Windows Time

$ClientTimeSourceHostName=$Windowstime.Split(".")[0]

# Checking If Client having current AD Server as TimeSource.

If ($ClientTimeSourceHostName -in $ADServers){
Write-Host "Computer having correct time source"

}else{
Write-Host "Computer not Using Correct TimeSource"
}

Script To Collect Os Info and Check Server State before run Commands.

# The Script combine multiple commands and combine the Result to Single output.
# Also this script check the target server before RUN commands.

function Get-LocalSysteminfo {
    param (
        $computername= (Read-Host "Enter-ComputerName")
    )

# Passing each server once at a time, to collect the data.

    foreach ($Server in $computername) {

# Before Passing Server into Script, Checking the server is online status, if server is online, data will be collect.

    $PingResult = Test-Connection $Server -Quiet
   
    If ($PingResult -eq $true){
           
    $OS = Get-WmiObject -Class Win32_operatingsystem -ComputerName $Server
    $bios = Get-wmiobject -Class Win32_bios -ComputerName $Server
    $disk = Get-wmiobject -Class win32_logicaldisk -ComputerName $Server

# Creating New PowerShell Object to Store the above information

    $obj = New-Object -TypeName psobject

    $obj | Add-Member -MemberType NoteProperty -Name Computername -Value $Server
    $obj | Add-Member -MemberType NoteProperty -Name OSVersion -Value $OS.Version
    $obj | Add-Member -MemberType NoteProperty -Name BiosSerial -Value $bios.serialnumber
    $obj | Add-Member -MemberType NoteProperty -Name disksize -Value $disk.size
    write-output $obj
    }
# If Server Unresponsive, Script will Return the name of the server. 
    else {
    Write-Host "Server is not Responding Ping $Server"
    }
}
}
Get-LocalSysteminfo no2,localhost,localhost,no5 |Format-Table -AutoSize