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!" 

  } 

}

No comments:

Post a Comment