Thursday, February 3, 2022

PS scripts

Compress / zip:
You run some cmd daily and its output you want to compress and send then 
If it is daily task then first run remove-item command
Remove-Item –path "path\Computers.Zip"

provide input file to Path variable
$compress = @{
Path= "path\Computers.csv"      
CompressionLevel = "Optimal"
DestinationPath = "path\Computers.Zip"
}

Compress-Archive @compress

use following variable in code for sending mail
$attachments = "path\Computers.Zip"

Remove disabled users from groups mentioned...

$GroupName = get-content "path\filename.csv"

$data = @()
$array = New-Object System.Object

foreach ($GroupMember in $GroupName)

{
   $user = Get-ADGroupMember -Identity $GroupMember -Recursive | %{Get-ADUser -Identity $_.distinguishedName -Properties Enabled | ?{$_.Enabled -eq $false}} 

            Remove-ADGroupMember -Identity $GroupMember -Member $user -Confirm:$false

   $array = get-ADGroupMember -Identity $GroupMember | Get-ADUser -Properties Enabled | Where {$_.Enabled -eq $false}  | Select-Object @{Name="Group";Expression={$GroupMember}},  name, @{n="Displayname";e={(Get-ADUser -Identity $_.sAMAccountName -Properties *).DisplayName}}

   $data+=$array
}

$data | Export-CSV path\filename.csv -NoTypeInformation

Action tab of task scheduler:
Action: Start a program
Program/script: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Add arguments: .\scriptname.ps1
Start in: Script folder location

if running an exe file then
Program/script: path of exe



To Run powershell scripts / ps1 scripts :

set-executionpolicy remotesigned (to allow ps1 scripts to run on local machines)

set-executionpolicy unrestricted (if the powershell script is not signed with a certificate.)

Accout lockout source script:
$UserName = Read-Host "Please enter username"
#Get main DC
$PDCEmulator = (Get-ADDomainController -Filter * | Where-Object {$_.OperationMasterRoles -contains "PDCEmulator"})
#Get user info
$UserInfo = Get-ADUser -Identity $UserName
#Search PDC for lockout events with ID 4740
$LockedOutEvents = Get-WinEvent -ComputerName $PDCEmulator.HostName -FilterHashtable @{LogName='Security';Id=4740} -ErrorAction Stop | Sort-Object -Property TimeCreated -Descending
#Parse and filter out lockout events
Foreach($Event in $LockedOutEvents)
  {
    If($Event | Where {$_.Properties[2].value -match $UserInfo.SID.Value})
    {

      $Event | Select-Object -Property @(
        @{Label = 'User'; Expression = {$_.Properties[0].Value}}
        @{Label = 'DomainController'; Expression = {$_.MachineName}}
        @{Label = 'EventId'; Expression = {$_.Id}}
        @{Label = 'LockoutTimeStamp'; Expression = {$_.TimeCreated}}
        @{Label = 'Message'; Expression = {$_.Message -split "`r" | Select -First 1}}
        @{Label = 'LockoutSource'; Expression = {$_.Properties[1].Value}}
      )


    }}


Create DNS records:

$ServerName = "hostname"
$domain = "pbi.global.pvt"
Import-Csv "C:\Users\xxx\Desktop\CreateDNS.csv" | ForEach-Object {

#Def variable
$Computer = "$($_.Computer).$domain"
$addr = $_.IP -split "\."
$rzone = "$($addr[2]).$($addr[1]).$($addr[0]).in-addr.arpa"

#Create Dns entries

dnscmd $Servername /recordadd $domain "$($_.Computer)" A "$($_.IP)"

#Create New Reverse Zone if zone already exist, system return a normal error
dnscmd $Servername /zoneadd $rzone /primary

#Create reverse DNS
dnscmd $Servername /recordadd $rzone "$($addr[3])" PTR $Computer
}

Excel should have column A as Computer and column B as IP

List of groups (under an OU) and its users :


$NewFileDate = (Get-date).AddDays(1).ToString("MM-dd-yyyy")
$GroupName = Get-ADGroup -SearchBase "OU=xx,OU=xx,DC=yy,DC=zz,DC=aa" -Filter * | Select-Object -ExpandProperty sAMAccountName
$Members = foreach ($GroupMember in $GroupName) {
   Get-ADGroupMember -Identity $GroupMember | Select-Object @{Name="Group";Expression={$GroupMember}}, name, @{n="Displayname";e={(Get-ADUser -Identity $_.sAMAccountName -Properties *).DisplayName}}
}

$Members | Export-CSV "\\hostname\Active Users Report\AWSGroupMembers\AWSGroupMembers_Report_$NewFileDate.csv" -NoTypeInformation

#####sending mail#####
$smtp = "smtp.domain"
##$smtp = "o365.mail.domain"
$to = @("user1","user2","user3","DL")
$from = "DL"
$attachments = "\\hostname\path\filename_$NewFileDate.csv"
$subject = "User Listing under the xx OU in AD-$NewFileDate"
$body = "Hi Team,<br><br>"
$body += "Please find attached file with User Listing under the xx groups in AD.<br><br>"   ####add text what u want as body of mail
$body += "Regards,<br>"
$body += "AD Team"
send-MailMessage -SmtpServer $smtp -To $to -From $from -attachments $attachments -Subject $subject -Body $body -BodyAsHtml

########### End of Script################





Account locked out Report:

[CmdletBinding()]
param (
    [ValidateNotNullOrEmpty()]
    [string]$UserName = "*"
   
)
   $server = "server hostname 1","server hostname 2","server hostname 3"
   $csv = @()
   foreach($serv in $server)
   {
if(test-connection $serv -erroraction silentlycontinue)
{

$csv +=   Get-WinEvent -ComputerName $serv -FilterHashtable @{LogName='Security';Id=4740} |
    Select-Object -Property TimeCreated,
        @{Label='UserName';Expression={$_.Properties[0].Value}},
        @{Label='computername';Expression={$_.Properties[1].Value}} |
Select-Object -Property TimeCreated, UserName, computername
}
else
{
$csv += "$server is not reachable"
}
     }
$date=get-date -format dd-MM-yyyy_HH.mm
$path="C:\Accountlockedout\Accountlockedout_"+$date+".csv"
$csv|sort username,computername -unique|Export-Csv "$path" -NoTypeInformation
start-sleep -seconds 3



#####sending mail#####
$smtp = "smtp.domain"
$to = @("DL1","DL2")
$from = "DL"
$attachments = "C:\path\filename_"+$date+".csv"
$subject = "User Account Lock Out Report"
$body = "Hi Team,<br><br>"
$body += "PFA, Report for the Account locked out users.<br><br>"   ####add text what u want as body of mail
$body += "Regards,<br>"
$body += "AD Team"
send-MailMessage -SmtpServer $smtp -To $to -From $from -attachments $attachments -Subject $subject -Body $body -BodyAsHtml
########### End of Script################

Consolidated Active users:

Import-Module ActiveDirectory
Get-ADUser -SearchBase "ou=xx,dc=zz,dc=yy,dc=aa" -Filter {enabled -eq $true} -properties * | select-object sAMAccountName,employeenumber, givenName, surName, DisplayName, whencreated, EmailAddress, DistinguishedName, LastLogonDate, Manager, @{n="ManagerName";e={(Get-ADUser -Identity $_.Manager -Properties displayName).DisplayName}}, Enabled | Export-Csv "C:\path\filename1.csv" -NoTypeInformation
Get-ADUser -SearchBase "ou=xx,ou=aa,dc=zz,dc=zz,dc=zz" -Filter {enabled -eq $true} -properties * | select-object sAMAccountName,employeenumber, givenName, surName, DisplayName, whencreated, EmailAddress, DistinguishedName, LastLogonDate, Manager, @{n="ManagerName";e={(Get-ADUser -Identity $_.Manager -Properties displayName).DisplayName}}, Enabled | Export-Csv "C:\path\filename2.csv" -NoTypeInformation
Get-ADUser -SearchBase "ou=xx,ou=zz,dc=aa,dc=qq,dc=qw" -Filter {enabled -eq $true} -properties * | select-object sAMAccountName,employeenumber, givenName, surName, DisplayName, whencreated, EmailAddress, DistinguishedName, LastLogonDate, Manager, @{n="ManagerName";e={(Get-ADUser -Identity $_.Manager -Properties displayName).DisplayName}}, Enabled | Export-Csv "C:\path\filename3.csv" -NoTypeInformation
import-csv C:\path\filename1.csv,C:\path\filename2.csv,C:\path\filename3.csv | export-csv "C:\path\filename4.csv" -NoTypeInformation

Mimic Membersship:
Import-Module ActiveDirectory

$copyfrom = Read-Host "Enter User that you are copying from"

$copyto = Read-Host "Enter User that you are copying to"

$user1 = Get-ADUser -Identity $copyfrom -Properties MemberOf

foreach ($group in ($user1 | Select-Object -ExpandProperty MemberOf))

{

add-ADGroupMember -Identity $group -Members $copyto


}

Group Membership with name and mail:

get-adgroupmember "groupname"| select name , @{n="UserName";e={(Get-ADUser -Identity $_.name -Properties displayName).DisplayName}}, @{n="mail";e={(Get-ADUser -Identity $_.name -Properties mail).mail}} >"groupname.txt"

Remove DNS and Computer entry:

$computer = get-content "C:\path.txt"

Foreach ($computer1 in $computer)

{

 Remove-DnsServerResourceRecord -Name $computer1 -RRType A -ZoneName domain -Force

 Remove-DnsServerResourceRecord -Name $computer1 -RRType AAAA -ZoneName domain -Force

 }

get-content "C:\path.txt" | foreach {dsquery computer -name $_ | dsrm -subtree -noprompt}

Move Computer:

$Computer = Get-Content "C:\path.txt"

Foreach($psitem in $Computer)

{

Get-ADComputer -Identity "$PSitem" | Move-ADObject -TargetPath 'OU=xx,OU=ss,DC=qq,DC=qq,DC=qq'

}

Get Computer:

Get-ADComputer -Filter * -SearchBase "OU=xx,OU=ss,DC=qq,DC=qq,DC=qq" -properties name,enabled | select-object name,enabled >computers.csv

User membership:

$users = get-content "C:\path.txt"
foreach ($users1 in $users)
{
Get-ADPrincipalGroupMembership -Identity $users1 | select name > $users1
echo $users1
}

Adding users to groups:

$user1 = get-content "C:\path.txt"

foreach ($user in $user1)
{
$group1 = Get-content "C:\path.txt"
foreach ($group in $group1)

{

add-ADGroupMember -Identity $group -Members $user

}
}

To set Kerberos attributes:

This account supports Kerberos AES 128 ,256 bit encryption
Do not require Kerberos preauthentication

get-content "C:\path.txt" | get-aduser | Set-ADAccountControl -doesnotrequirepreauth $true
get-content "C:\path.txt" | Set-ADUser -replace @{"msDS-SupportedEncryptionTypes"="24"}

Use -replace or -add based on account attribute field.

Phone attributes:

get-aduser -searchbase "OU=xx,OU=ss,DC=qq,DC=qq,DC=qq" -properties * | select samaccountname, mail, homePhone, pager, mobile, ipPhone, telephoneNumber, facsimileTelephoneNumber | Export-csv "C:\path.csv"

Get-User details:

  • Version 1:

#Read the CSV file - Map the Columns to Named Header (CSV File doesn't has Column Header)
$CSVData = Import-CSV -path "C:\Temp\Names.csv" -Header("Mailbox")
$RowCount = $CSVData.Count

$CurrentCount = 0

#Iterate through each Row in the CSV
foreach ($row in $CSVData)
{
    Write-host $row.Mailbox
    $currentUser = $row.Mailbox
    $GetCurrentUser = Get-ADUser -Identity $currentUser -Properties *        
    $manager = $GetCurrentUser.Manager.Replace("CN=","")
    $ManagerArray = $manager.split(",")
    $currentManager = $ManagerArray[1] + " " + $ManagerArray[0].replace("\","") 
    $currentUser + ":" + $currentManager | out-file -FilePath "C:\Temp\NewCSVExport.csv" -Append
}

  • Version 2:

Get-Content "C:\path.txt" | Get-ADUser -Properties * | select DisplayName,Name,givenName,SurName,samAccountName,UserPrincipalName,homemdb,mail,mailnickname,legacyExchangeDN,msexchRecipientTypeDetails,targetAddress,ObjectGUID,physicalDeliveryOfficeName,telephoneNumber,title,department,company,DistinguishedName,description,Enabled,EmployeeID,homeDirectory,homeDrive,profilePath,ScriptPath,@{N='accountExpires'; E={[DateTime]::FromFileTime($_.accountExpires)}},@{N='LastLogon'; E={[DateTime]::FromFileTime($_.LastLogon)}}, @{Name="proxyAddresses";Expression={($_.proxyAddresses | ForEach-Object {$_}) -join ";"}}, @{Name="memberOF";Expression={($_.MemberOF | ForEach-Object {$_}) -join ";"}} | export-csv c:\DMTUsers.csv -NoTypeInformation
  • User details of group 
get-content "path.txt" | Get-ADGroup -Properties mail,whenCreated,authOrig,unAuthOrig,dlMemRejectPerms,dlMemSubmitPerms,msExchRequireAuthtoSendTo | select Name,SamAccountName,GroupCategory,GroupScope,mail,whenCreated,distinguishedName,@{Name="authOrig";Expression={($_.authOrig | ForEach-Object {$_}) -join ";"}},@{Name="unauthOrig";Expression={($_.unauthOrig | ForEach-Object {$_}) -join ";"}},@{Name="dlMemRejectPerms";Expression={($_.dlMemRejectPerms | ForEach-Object {$_}) -join ";"}},@{Name="dlMemSubmitPerms";Expression={($_.dlMemSubmitPerms | ForEach-Object {$_}) -join ";"}},msExchRequireAuthtoSendTo |export-csv C:\groups.csv -NoTypeInformation

All active users:

Get-ADUser -SearchBase "DC=xx,DC=yy" -Filter {enabled -eq $true} -Properties sAMAccountName,displayname,EmailAddress,Enabled,Description,userPrincipalName | Export-Csv "\\FQDN\path\filename$(get-date -f yyyy-MM-dd).csv" -NoTypeInformation

Disabling user account:


$File=import-csv "C:\path.csv"
$TargetOU="OU=Withdrawn,OU=PBUsers,DC=pbi,DC=global,DC=pvt"

foreach ($entry in $File)

{

   Set-ADUser -Identity $($entry.name) -Enabled $false
     $UserDN = Get-ADUser $($entry.name) -properties distinguishedName
      Move-ADObject  -Identity $UserDN  -TargetPath $TargetOU


}
  • Scenario 1:

same user is part of two domains. One domain is taken as evidence. Disabled users on that day is generated  and given as input to other domain for validation. Other domain has samaccountname of prior domain in its description field. So compare description filed of users in this domain with samaccountname of input file.


$NewFileDate = (Get-date).AddDays(-1).ToString("MM-dd-yyyy")

$dt = import-csv "\\hostname\path\filename $NewFileDate.csv"
$dts = "\\hostname\path\filename $NewFileDate.csv""

$testpath = test-path $dts
if ($testpath -eq $true)
{

$data = @()
$array = New-Object System.Object
ForEach($aduser in $dt)

{

get-aduser -filter "description -eq 'column name (which has id) # $($aduser.Userid)'" | Set-ADUser -Enabled $false
$array = Get-ADUser -filter "description -eq 'column name (which has id) # $($aduser.Userid)'" -properties * | select samaccountname, enabled
$data+=$array

}

$data | Export-Csv -NoTypeInformation -Path "\\hostname\outputpath\outputfilename_$NewFileDate.csv"

}

#####sending mail#####
#$smtp = "smtp.domain"
#$to = @("DL1","DL2")
#$from = "DL1"
#$attachments = "\\hostname\outputpath\outputfilename_$NewFileDate.csv"
#$subject = " Daily Disables status-$NewFileDate" 
#$body = "Hi Team,<br><br>"
#$body += "PFA, Daily disables validation report file.<br><br>"   ####add text what u want as body of mail
#$body += "Regards,<br>"
#$body += "AD Team"
#send-MailMessage -SmtpServer $smtp -To $to -From $from -attachments $attachments -Subject $subject -Body $body -BodyAsHtml
########### End of Script################

  • Scenario 2
Same user in Two domains, one domain taken as reference to validate active users. Disabled users on that day are generated and given as input to other domain. 
The other domain contains samaccountname of prior domain in its employeeid field. So compare employee id filed of all users in tbis domain with samccountname from file and disabled the match.

Additional actions- remove group membership, update description , move the user account to specific OU.

$NewFileDate = (Get-date).AddDays(-1).ToString("MM-dd-yyyy")

#input file generated by IAM team
$dt = import-csv "\\hostname\path\filename $NewFileDate.csv"

$data = @()
$array = New-Object System.Object

#OU to which disabled user to be moved
$TargetOU = "OU=xx,OU=ww,DC=aa,DC=ww,DC=dd"

ForEach($aduser in $dt)
{
 if (get-aduser -filter "employeeid -eq '$($aduser.Userid)'")
   {

#Disable the user and update the description
      get-aduser -filter "employeeid -eq '$($aduser.Userid)'" | Set-ADUser `
      -Enabled $false `
      -description "$($NewFileDate) - Auto"

#Remove group membership of disabled user
      $adgroups = Get-ADPrincipalGroupMembership -Identity (get-aduser -filter "employeeid -eq '$($aduser.Userid)'")
      foreach ($singlegroup in $adgroups)
      {
       if ($singlegroup.SamAccountName -notlike "*Domain Users*")
       {
        Remove-ADPrincipalGroupMembership -Identity (get-aduser -filter "employeeid -eq '$($aduser.Userid)'") -MemberOf $singlegroup.SamAccountName -confirm:$false
       }
      }

#Move disabled user to target/ disabled OU
      $UserDN = Get-ADUser -filter "employeeid -eq '$($aduser.Userid)'" -properties distinguishedName
      Move-ADObject  -Identity $UserDN  -TargetPath $TargetOU 
   }
 $array =  Get-ADUser -filter "employeeid -eq '$($aduser.Userid)'" -properties * | select samaccountname, enabled 
 $data+=$array
}

#Output file path
$data | Export-Csv -NoTypeInformation -Path "\\fqdnhostanme\outputpath\outputfilename_$NewFileDate.csv"

#####sending mail#####
#$smtp = "smtp.domain"
#$smtp = "o365.mail.domain"
#$to = @("user1","user2")
#$from = "DL"
#$attachments = "\\fqdnhostanme\outputpath\outputfilename_$NewFileDate"
#$subject = " Daily Disables status-$NewFileDate" 
#$body = "Hi Team,<br><br>"
#$body += "PFA, Daily disables validation report file.<br><br>"   ####add text what u want as body of mail
#$body += "Regards,<br>"
#$body += "AD Team"
#send-MailMessage -SmtpServer $smtp -To $to -From $from -attachments $attachments -Subject $subject -Body $body -BodyAsHtml
#send-MailMessage -SmtpServer $smtp -To $to -From $from -attachments $attachments -Subject $subject -Body $body -BodyAsHtml
########### End of Script################

Change pwd at next logon:


  • Ticking “User must change password at next logon” = setting the value of “pwdLastSet” attribute to ‘0’
In other words setting value of attribute “pwdLastSet” to ‘0’ = Ticking “User must change password at next logon”

  • So if you want to check the users who are pending to change password at next logon then query for ‘pwdLastSet’ attribute, to see who has ‘0’ value set.

get-content "path.txt" | get-aduser -properties *| select samaccountname, pwdlastset

  • If you want to make a set of users to reset password at next logon then either write command to tick “User must change password at next logon” or command that sets value of attribute “pwdLastSet” to ‘0’

get-content "C:\path.txt" | Set-ADUser -ChangePasswordAtLogon 1


To change manager of user:

get-content "C:\path.txt" | Set-ADUser -Manager

Enable / Disable computer:

enable-ADAccount -Identity "hostname$"
disable-adaccount -Identity "hostname$"

$ is used at the end as samaccountname of computer ends with $

AD DC Replication hourly update:

Task Scheduler:
Program/script: "C:\Replication_status\Repl_Status_New.bat"
Add argumets: blank
Start in: blank

Repl_Status_New.bat file
@echo off
del C:\Replication_Status\AD_ReplicationStatus.txt
repadmin /replsum >> C:\Replication_Status\AD_ReplicationStatus.txt
cscript "C:\Replication_Status\Repl-Status_Mail_New.vbs"

Repl-Status_Mail_New.VBS
Set objEmail = CreateObject("CDO.Message")

Set fso = CreateObject("Scripting.FileSystemObject")
Set file=fso.OpenTextFile("C:\Replication_status\AD_ReplicationStatus.txt", 1)
Content=file.ReadAll

objEmail.From = "AD_Replication_Status@domain"
objEmail.To = "DL"
objEmail.CC = "user1"
objEmail.Subject = "AD Replication Status - Daily Check" 
objEmail.Textbody = "Hi Team," & vbCRLF
objEmail.Textbody = objEmail.Textbody & vbCRLF & "Please review the AD Replication Status and take corrective action in case of any issues." & vbCRLF
objEmail.Textbody = objEmail.Textbody & Content
objEmail.Textbody = objEmail.Textbody & vbCRLF & "Thanks."
objEmail.Textbody = objEmail.Textbody & vbCRLF & "AD Team"
objEmail.AddAttachment "C:\Replication_Status\AD_ReplicationStatus.txt"

objEmail.Configuration.Fields.Item _
    ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objEmail.Configuration.Fields.Item _
    ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _
        "smtp.domain" 
objEmail.Configuration.Fields.Item _
    ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objEmail.Configuration.Fields.Update

objEmail.Send

No comments:

Post a Comment