Hi Experts,
First of all, i am beginner of power-shell and as per my understanding i wrote script by doing googling for one of requirement in my company, but i think it can be compact by reducing duplicate steps,
Here i need your expert advice or help to review and modify script in proper way.
Requirement is:
1. Get Stale computer accounts - not logged-in from last 45 days. (excluding few OU's)
2. Check ping and DNS lookup and sort data based on the status e.g. Live.csv, RTO.csv, Unresolved.csv.
3. Move unresolved computers to stale OU and disable.
4. Send mail with attachment of 3 files mentioned in step no. 2
Note: For Live & RTO computers, need to captures DNS record time stamp, which will help to identify DNS record type e.g. Static or Dynamic
My power-shell code is below and its working fine but it is bit lengthy:
######Remove Exsisting Files###########Remove-Item C:\temp\test\O*.csv -Force
Remove-Item C:\temp\test\SendOnMail\U*.csv,C:\temp\test\SendOnMail\O*.csv -Force
####Variables##############
$DaysInactive = 45
$time = (Get-Date).Adddays(-($DaysInactive))
$inactivecomp = 'C:\temp\test\SendOnMail\StaleComputer_NotLoggedInLast45Days.csv'
$StaleComputers = (Import-Csv C:\temp\test\StaleComputer_NotLoggedInLast45Days.csv).Name
$Online = "C:\temp\test\Online.csv"
$RTO = "C:\temp\test\OfflineResolved.csv"
$UnResolved = "C:\temp\test\SendOnMail\UnResolved.csv"
#####Get-AD Computers that have not been logged-in from last 45 days######
Get-ADComputer -Filter {( LastLogonTimeStamp -lt $time)} -Properties LastLogonTimeStamp | where-object {($_.DistinguishedName -notlike "*OU=Corpo*") -and
($_.DistinguishedName -notlike "*OU=Project1*") -and ($_.DistinguishedName -notlike "*OU=Project2*")} |
select-object Name,DistinguishedName,DNSHostName,@{Name="LastLogon"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp)}} | sort -Property LastLogon |
export-csv $inactivecomp -notypeinformation -Force;
#################################
Start-Sleep -s 30
#####Check DNS Lookup & Ping ##################
ForEach ($Computer in $StaleComputers)
{
Try
{
$DNS = [System.Net.Dns]::GetHostEntry($Computer)
If (Test-Connection $Computer -Count 2 -ErrorAction SilentlyContinue)
{
"$Computer,$($DNS.HostName),$($DNS.AddressList[0].IPAddressToString),ONLINE" | Out-File -FilePath $Online -Append
}
Else
{
"$Computer,$($DNS.HostName),$($DNS.AddressList[0].IPAddressToString),OFFLINE" | Out-File -FilePath $RTO -Append
}
}
Catch
{
"$Computer,Could not resolve " | Out-File -FilePath $UnResolved -Append
}
}
###########################
Start-Sleep -s 30
#####Get-DNS record to identify Static & Dynamic Records - For RTO Computers######
$OfflineResolved = (Get-Content -Path C:\temp\test\OfflineResolved.csv | Select -skip 0 | ConvertFrom-Csv -Header Name -Delimiter ",").Name
$OfflineResults = @()
ForEach ($OffComputers in $OfflineResolved){
$OfflineResults += Get-DnsServerResourceRecord -ComputerName server1 -ZoneName test.com -RRType A -Name $OffComputers -ErrorAction Ignore | select-object -
Property Hostname,@{Name='RecordData';Expression={$_.RecordData.IPv4Address}},RecordType,TimeStamp
}
$OfflineResults | Export-Csv -Path C:\temp\test\SendOnMail\OfflineResolved_Computers.csv
########################
Start-Sleep -s 30
#####Get-DNS record to identify if its Static or Dynamic Records - For Online Computers####
$Online = (Get-Content -Path C:\temp\test\Online.csv | Select -skip 0 | ConvertFrom-Csv -Header Name -Delimiter ",").Name
$OnlineResults = @()
ForEach ($OnlineComputers in $Online){
$OnlineResults += Get-DnsServerResourceRecord -ComputerName Server1 -ZoneName test.com -RRType A -Name $OnlineComputers -ErrorAction Ignore | select-object -
Property Hostname,@{Name='RecordData';Expression={$_.RecordData.IPv4Address}},RecordType,TimeStamp
}
$OnlineResults | Export-Csv -Path C:\temp\test\SendOnMail\Online_Computers.csv
#######################
Start-Sleep -s 30
###Get all files for attaching in mail###########
[array]$attachments = Get-ChildItem "C:\temp\test\SendOnMail\" *.*
#####Send mail with required data attached in mail#########
$To = "xyz@test.com"
$From = "Do-NOT-Reply@test.com"
$smtpserver = "192.4.24.173"
$Subject = "Stale Computer Report"
$Body = "<p>Hi Team,</p>"
$Body += "<p>Please refer attached report for stale computer account that have not been logged-in from last 45 days.</p>"
$Body += "<p>Kindly verify records and delete it frm stale OU and upload report on SharePoint</p>"
$Body += "<p><strong>Regards,</strong></p>"
$Body += "<p>Windows Team</p>"
Send-MailMessage -From $From -To $To -Subject $Subject -SmtpServer $smtpserver -Attachments $attachments.fullname -BodyAsHtml $Body
####Moving Stale Computer To Stale OU##########
Start-Sleep -s 30
#####Move Unresolved Computers To Stale OU#######
$UnResolvedMove = (Get-Content -Path C:\temp\test\SendOnMail\UnResolved.csv | Select -skip 0 | ConvertFrom-Csv -Header Name -Delimiter ",").Name
$TargetOU = "OU=Stale_Comp_OU,OU=Test,DC=test,DC=com"
Foreach($DisabledOU in $UnResolvedMove){
Get-ADComputer $DisabledOU | Move-ADObject -TargetPath $TargetOU
}
#######################
Start-Sleep -s 30
###Disable Unresolved AD Computers#####
Get-ADComputer -SearchBase $TargetOU -Filter * | Disable-ADAccount
#######End Of Script##################