Here is the script im trying to run. I'm completely new to powershell. I'm not worried about the Sending email error as this is in my lab and is unable to communicate with my production server.
SCRIPT:
import-module ActiveDirectory
function sendMail([string]$bodytext, [string]$myregion)
{
Write-Host "Sending Email"
write-host $myregion
#SMTP server name
$smtpServer = "BLANK"
#Creating a Mail object
$msg = new-object Net.Mail.MailMessage
#Creating SMTP server object
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
#Email structure
$msg.From = "BLANK"
$msg.ReplyTo = ""
#$msg.To.Add("")
#$msg.To.Add("")
$msg.To.Add(")
$msg.subject = "***AD Clean Up - Moves - " + $myregion + " Workstations***"
$msg.body = $bodytext
#Sending email
$smtp.Send($msg)
}
function getResults($searchOU)
{
#get computers that exceed the cutoff and are not in the searched OU
$results=Get-ADComputer -Filter 'PasswordLastSet -le $cutoff' -SearchBase $searchOU -Properties PasswordLastSet | where {$_.DistinguishedName.IndexOf($excludeOU1) -le -1} | where {$_.DistinguishedName.IndexOf($excludeOU2) -le -1} |sort-object Name
return $results
}
$daysOld = 45
$today = Get-Date
$cutoff = $today.AddDays(-$daysOld)
#Specify OU to search and where to move to
$baseOU_USA = "BLANK"
$destinationOU_USA = "BLANK"
$region=$args[0].toUpper()
if ($region -eq "EMEA")
{
$baseOU=$baseOU_EMEA
$destinationOU = $destinationOU_EMEA
}
elseif ($region -eq "APJ")
{
$baseOU=$baseOU_APJ
$destinationOU = $destinationOU_APJ
}
else
{
write-host "USA"
$region="USA"
$baseOU=$baseOU_USA
$destinationOU = $destinationOU_USA
}
#specify strings to search for in OU name to exclude
$excludeOU1 = "Delete Pending"
$excludeOU2 = "Apple Macintosh"
$results=getResults($baseOU)
#put together the email body
$emailbody="Please review this list. If any of the machines are still valid please find out why they are not renewing their password with Active Directory.`r"
$emailbody+="Machines have been moved to: " + $destinationOU + " - No accounts have been deleted at this time.`r`r"
$emailbody+="Inactive machine count = " + $results.count + "`r"
$emailbody+="OU Searched = " + $baseOU + "`r"
$emailbody+="OUs Excluded = " + $excludeOU1 + ", " + $excludeou2 + "`r`r"
$emailbody+="Machines listed with password older than " + $daysOld + " days`r`r"
foreach ($machine in $results)
{
$passwordage= (-($machine.passwordlastset-$today).days)
$emailbody+=$machine.name + " | Password Age=" + $passwordage + " days | Password Changed= " + $machine.passwordlastset + "`r"
Move-ADObject -identity $machine.distinguishedName -TargetPath $destinationOU
}
write-host $region
sendmail $emailbody $region