28/3/14

Powershell Script - Kiểm tra đồng bộ giữa các Domain Controller

Write-Host ""

$Target_rep = hostname
$date_rep =  Get-Date

$Filename_rep = "C:\Log_Replication\" + $Target_rep + "_" + $date_rep.Hour + $date_rep.Minute + "_" + $Date_rep.Day + "-" + $Date_rep.Month + "-" + $Date_rep.Year + ".hta"



Clear-Host;
Write-host ""
Write-host "Nhap bat ky ky tu nao, se thuc hien kiem tra Replication tai may chu Domain controller hien tai"
write-host "Nhap '*' de thuc hien kiem tra Replication tren tat ca Domain Controller." -foregroundcolor red -backgroundcolor yellow
$SERVERS = (Read-Host "Kiem tra Replication tren Domain Controller")
if ($SERVERS -ne "*")
{
Write-host ""
write-host "Dang kiem tra........"
$workfile = repadmin.exe /showrepl /csv}
else
{
Write-host ""
write-host "Dang kiem tra........"
#Check the Replication with Repadmin
$workfile = repadmin.exe /showrepl * /csv
}
#if ($error -eq $null)
#{

$Report_Rep = @"

TEST REPLICATION











verify AD replication status on Domain controller:$Target_rep

Version 1.0 by Pham Duy Hieu
Report generated on $Date_rep












"@


$results = ConvertFrom-Csv -InputObject $workfile | where {$_.'Number of Failures' -ge 1}
$CountFail = $results.count
#$results_show = ConvertFrom-Csv -InputObject $workfile
write-host ""
#$results_show | select "Source DSA", "Naming Context", "Destination DSA" ,"Number of Failures", "Last Failure Time", "Last Success Time", "Last Failure Status"

#$results_show | select "Source DSA", "Naming Context", "Destination DSA" ,"Number of Failures", "Last Failure Time", "Last Success Time", "Last Failure Status" | ConvertTo-Html > C:\Log_Replication\Show_Test_replicate.hta

#Here you set the tolerance level for the report
$results = $results | where {$_.'Number of Failures' -gt 1 }

cls
if ($results -ne $null ) {
write-host ""
write-host "Replication Errors: $CountFail" -foregroundcolor red -backgroundcolor yellow
write-host ""
#$results | select "Source DC", "Naming Context", "Destination DC" ,"Number of Failures", "Last Failure Time", "Last Success Time", "Last Failure Status"
    #$results | select "Source DC", "Naming Context", "Destination DC" ,"Number of Failures", "Last Failure Time", "Last Success Time", "Last Failure Status" | ConvertTo-Html > C:\Log_Replication\Test_replicate_fail.hta

$SourceDSA = $results | select 'Source DSA'
#write-host $SourceDSA



} else {


write-host ""
    write-host "There were no Replication Errors" -foregroundcolor red -backgroundcolor yellow
write-host ""
}
#===========================================================================
$Report_rep+= @"
 



Success






  Source DSA
  Naming Context
  Destination DSA
Number of Failures
Last Failure Time
Last Success Time
Last Failure Status

"@
#============================================================================
$success = ConvertFrom-Csv -InputObject $workfile | where {$_.'Number of Failures' -le 0}
#write-host success_count = $success.count
foreach ($row in $success)
{

$SourceDSA = $row.'Source DSA'
$NamingContext = $row.'Naming Context'
$DestinationDSA = $row.'Destination DSA'
$NumberofFailures = $row.'Number of Failures'
$LastFailureTime = $row.'Last Failure Time'
$LastSuccessTime = $row.'Last Success Time'
$LastFailureStatus = $row.'Last Failure Status'

#============================================================================


$Report_rep+=  " "
$Report_rep+=  "$SourceDSA
" $Report_rep+=  "$NamingContext
" $Report_rep+=  "$DestinationDSA
" $Report_rep+=  "$NumberofFailures
" $Report_rep+=  "$LastFailureTime
" $Report_rep+=  "$LastSuccessTime
" $Report_rep+=  "$LastFailureStatus
" $Report_rep+=  "
"}
#===================================================================================
$Report_rep+= @"




"@

#==============================================================

$Report_rep+= @"



Failure






  Source DSA
  Naming Context
  Destination DSA
Number of Failures
Last Failure Time
Last Success Time
Last Failure Status


"@



#==================================================================

$fail = ConvertFrom-Csv -InputObject $workfile | where {$_.'Number of Failures' -ge 1}
#write-host $fail_count = $fail.count
foreach ($row_fail in $fail)
{
$SourceDSA_fail = $row_fail.'Source DSA'
$NamingContext_fail = $row_fail.'Naming Context'
$DestinationDSA_fail = $row_fail.'Destination DSA'
$NumberofFailures_fail = $row_fail.'Number of Failures'
$LastFailureTime_fail = $row_fail.'Last Failure Time'
$LastSuccessTime_fail = $row_fail.'Last Success Time'
$LastFailureStatus_fail = $row_fail.'Last Failure Status'



#==============================================================


$Report_rep+=  " "
$Report_rep+=  "$SourceDSA_fail
" $Report_rep+=  "$NamingContext_fail
" $Report_rep+=  "$DestinationDSA_fail
" $Report_rep+=  "$NumberofFailures_fail
" $Report_rep+=  "$LastFailureTime_fail
" $Report_rep+=  "$LastSuccessTime_fail
" $Report_rep+=  "$LastFailureStatus_fail
" $Report_rep+=  "
"
#==============================================================
}
$Report_rep+= @"




"@

#==============================================================



$Report+= @"


"@
write-host ""
write-host "Dang tao Report........."
$Report_rep | out-file -encoding ASCII -filepath $Filename_rep

write-host ""
Write-Host "Report xem tai folder C:\Log_Replication" -foregroundcolor red -backgroundcolor yellow
write-host ""
#}else
#{write-host $error}

PowerShell Script - Create User Domain From CSV File



Chạy trên máy chủ Domain controller 2008 r2 với account có quyền tạo mới User Domain.

Đoạn Script này giúp bạn tạo User Domain từ một file CSV cho trước.
Trong file excel cần nhập các thông tin như hình dưới:


các giá trị từ cột A đến cột E bắt buộc phải nhập. Sau khi điền đầy đủ thông tin save as dưới định dạng file CSV và để cùng thư mục chạy file .ps1


import-module ActiveDirectory
$csv = import-csv -path .\username.csv
foreach ($row in $csv)
{
$dName = $row.name
$SamAccountName = $row.samaccountname
$firstName = $row.firstname
$lastName = $row.lastname
$OU = $row.ou
$passwd = $row.password
$department = $row.department
$description = $row.description

$Userprincipalname_temp = $row.Userprincipalname


$Userprincipalname = $SamAccountName + "@" + $Userprincipalname_temp


New-ADUser -Name $dName -SamAccountName $SamAccountName -GivenName $firstName -Surname $lastName -Path $OU -AccountPassword (convertto-securestring $passwd -asplaintext -force) -ChangePasswordAtLogon $false -Department $department -Description $description -UserPrincipalName $Userprincipalname -Enabled $true

}


==================================================
bqhoan@gmail

6/3/14

Script to Move AD User Objects to another OU depending on an Attribute

# 2012, Tom Schindler
# Moves User Accounts from the given Root OU into sub OUs by looking up the company Attribute of the User Object
# If the OU does not exist, it will be created (the regular expression filter is removing special characters)
 
Import-Module ActiveDirectory
$RootOU = "OU=Guests,DC=mydomain,DC=local"
$LogFile=".\ADS_MoveUsersToCompanyOU.txt"
 
$strFilter = "(&(objectCategory=User))"
 
$objDomain = New-Object System.DirectoryServices.DirectoryEntry "LDAP://$RootOU"
 
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = "OneLevel"
 
$colProplist = "name", "company", "sAMAccountName", "cn"
 
Function Write-Log {
     [cmdletbinding()]
 
    Param(
     [Parameter(Position=0)]
     [ValidateNotNullOrEmpty()]
     [string]$Message
     )
 
     Write-Host $Message
  Write-Output "$(Get-Date) $Message" | Out-File -FilePath $LogFile -Append
 
} #end function
 
 
foreach ($i in $colPropList){
 $objSearcher.PropertiesToLoad.Add($i)
 }
 
$colResults = $objSearcher.FindAll()
 
foreach ($objResult in $colResults) {
 $objItem = $objResult.Properties; 
 $strCompany = $objItem.company
 $strCN = $objItem.cn
 $strName = $objItem.name
 $strCompany = [System.Text.RegularExpressions.Regex]::Replace($strCompany,"[^1-9a-zA-Z_ ]","")
 
 Write-Log "INFO    User found         : $strName"
 Write-Log "INFO    Company            : $strCompany"
 Write-Log "INFO    Canonical Name     : $strCN"
 Write-Log "INFO    Distinguished Name : $strdistinguishedName"
 
 if (!$strCompany) {
  Write-Log "WARNING No Company Name found for User: $strName"
  }
 else {
  $fullOU = "OU=$strCompany,$RootOU"
 
  $OUExists = [ADSI]::Exists("LDAP://$fullOU")
  if ($OUExists) {
   Write-Log "INFO    OU exists already:$fullOU"
   }
  else {
   Write-Log "INFO    Creating new OU: $fullOU"
   $objDomain = [ADSI]"LDAP://$RootOU"
   $objOU = $objDomain.Create("OrganizationalUnit", "OU=$strCompany")
   try {
    $objOU.SetInfo()
    }
   catch {
    Write-Log "ERROR  Unable to set AD Info (Creating OU: $strCompany)"
    Write-Log "ERRMSG $($_.Exception.Message)"
    }
   }
   try {
    Move-ADObject -Identity "CN=$strCN,$RootOU" -TargetPath "OU=$strCompany,$RootOU"
    }
   catch {
    Write-Log "ERROR  Unable to move User:CN=$strCN,$RootOU"
    Write-Log "$($_.Exception.Message)"
    }   
  }
 }

Move list of user accounts to OU

On Error Resume Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("UsersList.txt", ForReading) '--- LIST OF USERNAMES
Set objOU = GetObject("LDAP://OU=UserAccounts,DC=domain,DC=com") '--- ADD YOUR PATH TO THE OU
Const ForReading = 1
Dim arrFileLines()
i = 0
Do Until objFile.AtEndOfStream
Redim Preserve arrFileLines(i)
arrFileLines(i) = objFile.ReadLine
i = i + 1
Loop
objFile.Close


For Each strLine in arrFileLines
strLDAP = GetDN(strLine)
objOU.MoveHere _
    "LDAP://" & strLDAP & "", vbNullString
Next


Function GetDN(UserID) 


      Set objConn = CreateObject("ADODB.Connection")
      objConn.Provider = "ADsDSOObject"
      objConn.Open "Active Directory Provider"
      
      Dim Base, Filter, Attr, Level, Server
      Server = "DC1" '--- NAME OF DOMAIN CONTROLLER
      
      Base = " & Server & "/DC=domain,DC=com>;" '--- ADD YOUR DOMAIN
      Filter = "(&(objectClass=user)(objectCategory=person)(samAccountName=" & UserID & "));"
      Attr = "distinguishedName;"
      Level = "SubTree"
      
      Set RecordSet = objConn.Execute(Base & Filter & Attr & Level)
      
      RecordSet.MoveFirst
      While Not RecordSet.EOF
            GetDN = RecordSet.Fields(0).Value
            RecordSet.MoveNext
      Wend 

End Function 

PowerShell to Disable users account & move them to different OU using CSV

########################################################################### 
# NAME:                Script to disable users account and move them to different OU using CSV 
# AUTHOR:              Imran Pathan 
# COMMENT:             All you need is fill up the Disable user account csv with saMAccountName & OU to move to.  
# VERSION HISTORY:     1.0 
# 1.0 12/19/2012 - Initial release 
############################################################################ 
$UsersToDisbableList=IMPORT-CSV C:\Imran\DisableUsers.csv  
$PrimaryDC = 'PDC002.yourdomain.local' 
$DomainName = 'yourdomain' 
Clear-Host 
Connect-QADService -service $PrimaryDC 
 
Function DisableUsers 
{ 
    Param( 
        [string] $_SamAccountName, 
        [string] $_MoveTOOU 
        ) 
    write-host ("User: $_SamAccountName") 
    Write-Host ("Move to OU: $_MoveTOOU") 
 
Get-ADUser $_SamAccountName | Set-ADUser -Enabled $false 
Start-Sleep -s 2 
Move-QADObject -Identity $_SamAccountName -NewParentContainer $_MoveTOOU 
Start-Sleep -s 2 
} 
 
FOREACH ($User in $UsersToDisbableList) { 
    DisableUsers $User.SamAccountName $User.MoveTOOU 
}