Powershell Script Help (Get-Process and send output via SMTP) - windows

I'm trying to make e Powershell script to check a specific service(name) with Status and StartType and additional information like time and date of the servers and server names.
List of servers from .txt is only the FQDN's.
I have the desired output in powershell but can't get it properly to send via SMTP.
In one case it doesn't show the state or won't show to processes only the names of the servers and all the information is plain text not in containers for the different servers.
Desired output :desired output in powershell need to transfer to smtp email
$ServerList = Get-Content -Path "C:\new_folder\servers.txt"
Foreach ($server in $ServerList){
$time = "---"
$time = ([WMI]'').ConvertToDateTime((gwmi win32_operatingsystem -computername $server).LocalDateTime)
$server + ', ' + $time
Get-Service -ComputerName "$server" | where-object {$_.name -like '*goge*'} | Select #{Name="server";Expression={$server}},Name,DisplayName,StartType,Status
}send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Body $body -BodyAsHtml -Priority high

Try to use this little fix, i leave comments
$ServerList = Get-Content -Path "C:\new_folder\servers.txt"
$array=#() #array which will contain result get-service
Foreach ($server in $ServerList){
$time = "---"
$time = ([WMI]'').ConvertToDateTime((gwmi win32_operatingsystem -computername $server).LocalDateTime)
$server + ', ' + $time
#add to our array result of each get-service from servers
$array+=Get-Service -ComputerName "$server" | where-object {$_.name -like '*goge*'} | Select #{Name="server";Expression={$server}},Name,DisplayName,StartType,Status
}
send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Body $array -BodyAsHtml -Priority high

Related

Powershell, send email for each user that has been disabled to their managers

So after a-lot of help, there is a script that will search users that were disabled for the past 14 days + show their managers name + email and date when they were disabled:
$ou = "my-ou"
$date = (Get-Date).AddDays(-14)
$todaydate = Get-Date -DisplayHint Date
$disabledAccounts = Get-aduser -filter {Enabled -eq $false -and Modified -ge $date } -SearchBase $ou -Properties Modified,manager | select samaccountname,Modified,manager
#$ManagerName = ''
$Body = ”
<html>
<body>
<p>Dear $ManagerName,<br>
The user $userName has been disabled on $todaydate .<br
</body>
</html>”
ForEach($disabledAccount in $disabledAccounts){
$manager = get-aduser -property emailaddress,DisplayName $disabledAccount.manager
$ManagerName= $manager.Displayname
$userName = $disabledAccount.samaccountname
Send-MailMessage -To $manager.UserPrincipalName -From ‘test#email.com’ -Subject ‘Disabled account’ -Body $Body -SmtpServer ‘mysmtp’ -BodyAsHtml -Priority High
}
The problem for now that this script only sent email for 1 user when in my test i have 2 disabled users in this period of time.
And the first command with "Get-Aduser" i see both of the users, and in the second one "Get-aduser" i see only 1.
$ou = "my ou direction"
$date = (Get-Date).AddDays(-14)
$diabledAccounts = Get-ADUser -Filter {Enabled -eq $false -and Modified -ge $date } -SearchBase $ou -Properties Modified,manager | select samaccountname,Modified,#{n='Manager';e={(Get-ADUser $.manager).name}},#{n='ManagerEmail';e={(Get-ADUser $.manager -properties mail).mail}}
ForEach($diabledAccount in $diabledAccounts){
Send-MailMessage -To $diabledAccount.ManagerEmail -Subject 'Disabled account' -Body "Account $diabledAccount.samaccountname has been disabled in the last 14 days" -SmtpServer ''
}
I answered something like this on Spice works
$ou = “my_ou”
$date = (Get-Date).AddDays(-14)
$disabledAccounts = Get-aduser -filter {Enabled -eq $false -and Modified -ge $date } -SearchBase $ou -Properties Modified,manager | select samaccountname,Modified,manager
$ManagerName = ''
$Body = ”
<html>
<body>
<p>Dear $ManagerName,<br>
The user $userName has been disabled on .<br
</body>
</html>”
ForEach($disabledAccount in $disabledAccounts){
$manager = get-aduser -property emailaddress,DisplayName $disabledAccount.manager
$ManagerName= $manager.Displayname
$userName = $disabledAccount.samaccountname
Send-MailMessage -To $manager.ManagerEmail -From ‘myemail#’ -Subject ‘Disabled account’ -Body $Body -SmtpServer ‘mysmtp server’ -BodyAsHtml -Priority High
}

Powershell Get-Service report wrong information

I've created a powershell script to list all domain controllers under current trusted forest, and than check each individual server for specific services if it's running or not and send an email with report.
I found 2 issues so far.
Get-Service -name "MyService" -ComputerName $myComputer "will say no service is found with that name, but if I list all the services : Get-Service -ComputerName $myComputer it will say "This operation might require other privileges." This is a problem because I'm reporting that the service doesn't exist but it is actually there.
For some reason if I just run the powershell script from command line manually it lists way more servers and most of the info is correct. But I schedule the powershell script from windows task manager with that same account the information is all wrong and it reports way less servers.
Script:
#$domain = [system.directoryservices.activedirectory.domain]::GetCurrentDomain().Name
#$numerOfDomainControlers= nslookup $domain
Clear-Content .\log.txt
$startTime = Get-Date
$allDCs = ((Get-ADForest).Domains | %{ Get-ADDomainController -Filter * -Server $_ } | Where-Object { $_.hostname -notlike '*root*' }).hostname
foreach( $allDC in $allDCs){
$testConnection = Test-Connection $allDC -Quiet -Count 1 -ErrorAction SilentlyContinue
Write-Host
if($testConnection -like "true") {
$SyncStatus = Get-Service -name "MyServicesName" -ComputerName $allDC -ErrorAction SilentlyContinue
if($SyncStatus.length -eq 0) {
Write-Host "MyServicesName doesn't exists on:"$allDC
$SyncStatus = "MyServicesName doesn't exists on:" + $allDC
$logs = $SyncStatus |Out-File .\log.txt -Append
}
else{
write-host "MyServicesName on "$allDC "is: " $SyncStatus.status
$SyncStatus = "MyServicesName on " + $allDC + "is: " + $SyncStatus.status
$logs = $SyncStatus |Out-File .\log.txt -Append
}
}
else
{
Write-Host "Test Connection to Server failed:"$allDC
$SyncStatus = "Test Connection to Server failed:" + $allDC
$logs = $SyncStatus |Out-File .\log.txt -Append
}
}
$endTime = Get-Date
$totalTime = New-TimeSpan -start $startTime -end $endTime
Write-Host $totalTime
$logs = "Total Time in Seconds:" + $totalTime |Out-File .\log.txt -Append
#send Email
$logs = Get-Content .\log.txt
$serverName = $env:computername
$LogTime = Get-Date -Format "MM/dd/yyyy hh:mm:ss"
$FromAddress = "email.com"
$ToAddress = "email.com"
foreach($log in $logs)
{
$Messagebody = $messagebody + $log + "`r`n" |Out-String
}
[string] $MessageSubject ="Status Report runing on " + $serverName +" " + $endTime
$SendingServer = "server"
Send-MailMessage -to $ToAddress -from $FromAddress -subject $MessageSubject -smtpServer $SendingServer -body $Messagebody -Attachments .\log.txt

powershell script to compare two text files and output should be a notification like email

I'm having a PowerShell script for comparing two text files and displaying the output:
Compare-Object $(Get-Content c:\scripts\x.txt) $(Get-Content c:\scripts\y.txt) -includeequal
But I want the output in the form of a notification, like an Email...
How can I forward the output to an Email-Body and then send it the mail?
To put the output comparison into an Email and send it over gmail, you can use the Send-MailMessage command like this:
$From = "YourEmail#gmail.com"
$To = "ToMail#Domain.com"
$Cc = "CCMail#Domain.com"
$Subject = "String Comparison"
$comparison = (Compare-Object (Get-Content c:\scripts\x.txt) (Get-Content c:\scripts\y.txt) -includeequal).InputObject
foreach($line in $comparison)
{
$Body+= $line
}
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject -Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl -Credential (Get-Credential)
For more information look into Send-MailMessage and Google SMTP Config

Delete email attachment after sending powershell

I have wrote a script for automated email using powershell.
The email sends however how can i configure it so that the file that is attached is moved to another folder inside the folder it was originally located?
#Searches dir for list , formats
$Attachment = Get-ChildItem -Path $dir -Filter "*$($Region.name)*" -Recurse
$AttachmentName = $Attachment.BaseName
$Subject = "$AttachmentName # $Time"
$Body = "Please find attached the file needed for $($Region.name).
Regards,
Me
"
#Actions Email
Send-MailMessage -From $Region.From -To $Region.To -CC $Region.Cc -Subject $Subject -Body $Body -SmtpServer $SMTPServer -Attachments $Attachment.FullName
Move-Item Get-ChildItem -Path $dir -Filter "*$($Region.name)*" -Recurse "C:\Users\users\Desktop\MissingImageLists\OldLists"
}
Remove your Move-Item command and replace it with:
$Attachment | Move-Item -Destination "$dir\subfolder"

Send-MailMessage: Cannot validate argument on parameter 'Subject'

This error appears when running the script below:
Send-MailMessage : Cannot validate argument on parameter 'Subject'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
The email still sends successfully and the subject appears correctly.
$dir = "C:\Users\user\Desktop\Lists\TodaysLists"
$SMTPServer = "192.168.1.111"
$Time = (Get-Date).ToString('MM/dd/yyyy hh:mm tt')
$japan = #{
Name = 'Japan'
From = "me#me.com
To = "you#me.com"
Cc = "him#me.com"
}
$ireland = #{
Name = 'Ireland'
From = "me#me.com
To = "you#me.com"
Cc = "him#me.com"
}
$Regions = #()
$Regions += New-Object PSObject -Property $japan
$Regions += New-Object PSObject -Property $ireland
foreach ($Region in $Regions) {
$Attachment = Get-ChildItem -Path $dir -Filter "*$($Region.Name)*" -Recurse
$AttachmentName = $Attachment.BaseName
$Subject = "$AttachmentName"
$Body = "Please find attached the Report for $($Region.Name).
Produced # $Time
Regards,
John Doe
"
Send-MailMessage -From $Region.From -To $Region.To -CC $Region.Cc -Subject $Subject -Body $Body -SmtpServer $SMTPServer -Attachments $Attachment.FullName
$Attachment | Move-Item -Destination "C:\Users\user\Desktop\Lists\oldLists"
}
My guess would be that $Attachment = Get-ChildItem -Path $dir -Filter "*$($Region.Name)*" -Recurse is not returning any files for one or more of the regions, so $Subject ends up being $null.
You could either check for that state and perhaps throw a warning instead of attempting to send the mail, or another way to work around the error (and get an email sent but with a blank subject) would be to add some other (guaranteed) text to $subject. E.g:
$Subject = "$($Region.Name): $AttachmentName"
Although then I suspect it would complain about -Attachments being null.
To add a check/throw warning, you could do the following:
foreach ($Region in $Regions) {
$Attachment = Get-ChildItem -Path $dir -Filter "*$($Region.Name)*" -Recurse
If ($Attachment) {
$AttachmentName = $Attachment.BaseName
$Subject = "$AttachmentName"
$Body = "Please find attached the Report for $($Region.Name).
Produced # $Time
Regards,
John Doe
"
Send-MailMessage -From $Region.From -To $Region.To -CC $Region.Cc -Subject $Subject -Body $Body -SmtpServer $SMTPServer -Attachments $Attachment.FullName
$Attachment | Move-Item -Destination "C:\Users\user\Desktop\Lists\oldLists"
} Else {
Write-Warning "One or more files named $($Region.Name) were not found in $dir. Mail not sent."
}
}

Resources