I've got this script that I found that simply sends the time the script was run in an e-mail to the recipient.
function send-email
{
$time = get-date
$EmailFrom = “from”
$EmailTo = “To”
$Subject = “ADX Has Been Deployed”
$Body = “Script has been used on: ” + $time
$SMTPServer = “smtp.gmail.com”
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential(“e-mail address”, “password”);
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
}
send-email
This works a treat, however when I try and add some data into the body of the e-mail using the below code (hostname, IP Address, etc), the data is returned as a complete string.
$a = #()
$systeminfo = get-wmiobject win32_computersystem | select *
foreach ($item in $systeminfo)
{
$a = $item
}
Basically, what I'm after is for the data to be presented in the e-mail one line at a time.
Any ideas?
Thanks
$a = #()
$systeminfo = get-wmiobject win32_computersystem | select *
foreach ($item in $systeminfo)
{
$a += $item
}
$body = [string]::Join("`n", $a)
Related
I have a PowerShell command that will get an output of how many CAL's I have installed and how many are used. I would like to instead of write-host, change it to a variable so that I can add it to the body of an email and have it run on a schedule, to email me weekly reports on usage, I would like to have the variable something like $report as shown in the $body of the email, this is what I have so far..
$fileName = (Invoke-WmiMethod Win32_TSLicenseReport -Name GenerateReportEx).FileName
$summaryEntries = (Get-WmiObject Win32_TSLicenseReport|Where-Object FileName -eq $fileName).FetchReportSummaryEntries(0,0).ReportSummaryEntries
$summaryEntries|ForEach {Write-Host $_.ProductVersion $_.TSCALType "Installed:" $_.InstalledLicenses "Issued:" $_.IssuedLicenses}
$EmailTo = "itgroup#contonso.com"
$EmailFrom = "admin#contonso.com"
$user = 'admin#contonso.com'
$password = Unprotect-CmsMessage -Path C:\Scripts\Powershell\EncryptedSecret.txt
$Subject = "Alert: CAL USAGE "
$Body = "Alert; $Report"
$SMTPServer = "smtp#contonso.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
$SMTPClient.EnableSsl = $false
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($user, $password)
$SMTPClient.Send($SMTPMessage)
I have used both parts of this script separately, but I would like to join them together, to make more useful. Thanks in advance PowerShell newbie..
Here is the full code that I used to get this to work, simply changing 'Write-Host' to 'Write-Output'
$fileName = (Invoke-WmiMethod Win32_TSLicenseReport -Name GenerateReportEx).FileName
$summaryEntries = (Get-WmiObject Win32_TSLicenseReport|Where-Object FileName -eq $fileName).FetchReportSummaryEntries(0,0).ReportSummaryEntries
$Report = $summaryEntries|ForEach {Write-Output $_.ProductVersion $_.TSCALType "Installed:" $_.InstalledLicenses "Issued:" $_.IssuedLicenses}
$EmailTo = "itgroup#contonso.com"
$EmailFrom = "admin#contonso.com"
$user = 'admin#contonso.com'
$password = Unprotect-CmsMessage -Path C:\Scripts\Powershell\EncryptedSecret.txt
$Subject = "RDS CAL USAGE REPORT"
$Body = "Alert; $Report"
$SMTPServer = "smtp#contonso.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
$SMTPClient.EnableSsl = $false
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($user, $password)
$SMTPClient.Send($SMTPMessage)
I have a piece of code comparing two values, and if the condition is satisfied it sends out an email. But it is not working, help is appreciated.
code:
$filesize = Get-ChildItem $filename | Select-Object Length | Format-Wide
$filesize
$num=1265
$num
if("$filesize" -gt "$num")
{
$SMTPServer = "10.20.19.94"
$SMTPPort = 25
$username = "vcenter#somosadc.com"
#Define the receiver of the report
$to = "jeevan.m2#hcl.com"
$subject = "VM Snapshot Report"
$body = "VM Snapshot Report"
$attachment = new-object Net.Mail.Attachment($filename)
$message = New-Object System.Net.Mail.MailMessage
$message.subject = $subject
$message.body = $body
$message.to.add($to)
$message.from = $username
$message.attachments.add($attachment)
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $false
#$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message)
write-host "Mail Sent"
}
output:
1262
1265
Mail Sent
Why is it sending email if $filesize=1262 is less than $num=1265. It is killing me.
Because you're not comparing two numbers, you're comparing two strings.
Remove the Format-Wide command from the first pipeline, and remove the quotes around the arguments in your if condition:
$filesize = Get-ChildItem $filename | Select-Object Length
$num = 1265
if($filesize.Length -gt $num) {
<# ... #>
}
I've been browsing the web trying to find a way if possible to email a low disk space alert from a Gmail account to a shared mail box using power shell but Im struggling with a query I've managed to piece together.
$EmailFrom = "FromEmail#Gmail.com"
$EmailTo = "ToEmail#Gmail.com"
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("Username", "Password");
$Computers = "Local Computer"
$Subject = "Disk Space Storage Report"
$Body = "This report was generated because the drive(s) listed below have less than $thresholdspace % free space. Drives above this threshold will not be listed."
[decimal]$thresholdspace = 50
$tableFragment = Get-WMIObject -ComputerName $computers Win32_LogicalDisk `
| select __SERVER, DriveType, VolumeName, Name, #{n='Size (Gb)' ;e={"{0:n2}" -f ($_.size/1gb)}},#{n='FreeSpace (Gb)';e={"{0:n2}" -f ($_.freespace/1gb)}}, #{n='PercentFree';e={"{0:n2}" -f ($_.freespace/$_.size*100)}} `
| Where-Object {$_.DriveType -eq 3} `
| ConvertTo-HTML -fragment
$regexsubject = $Body
$regex = [regex] '(?im)<td>'
if ($regex.IsMatch($regexsubject)) {$smtpclinet.send($fromemail, $EmailTo, $Subject, $Body)}
Script runs but nothing happens, any help would be fantastic!!!
My version would be longer because I'd have made a substitute for Send-MailMessage such that swapping between mine and Send-MailMessage is trivial.
This is one possible way of doing it. There are good uses for the Fragment parameter on ConvertTo-Html, but not much of a justification to do so here.
This is a script and expected to be a .ps1 file. Mandatory things I don't really want to hard-code beyond a default are set in the param block.
param(
[String[]]$ComputerName = $env:COMPUTERNAME,
[Decimal]$Theshold = 0.5,
[PSCredential]$Credential = (Get-Credential)
)
#
# Supporting functions
#
# This function acts in much the same way as Send-MailMessage.
function Send-SmtpMessage {
param(
[Parameter(Mandatory = $true, Position = 1)]
[String[]]$To,
[Parameter(Mandatory = $true, Position = 2)]
[String]$Subject,
[String]$Body,
[Switch]$BodyAsHtml,
[String]$SmtpServer = $PSEmailServer,
[Int32]$Port,
[Switch]$UseSSL,
[PSCredential]$Credential,
[Parameter(Mandatory = $true)]
[String]$From
)
if ([String]::IsNullOrEmtpy($_)) {
# I'd use $pscmdlet.ThrowTerminatingError for this normally
throw 'A value must be provided for SmtpServer'
}
# Create a mail message
$mailMessage = New-Object System.Net.Mail.MailMessage
# Email address formatting si validated by this, allowing failure to kill the command
try {
foreach ($recipient in $To) {
$mailMessage.To.Add($To)
}
$mailMessage.From = $From
} catch {
$pscmdlet.ThrowTerminatingError($_)
}
$mailMessage.Subject = $Subject
$mailMessage.Body = $Body
if ($BodyAsHtml) {
$mailMessage.IsBodyHtml = $true
}
try {
$smtpClient = New-Object System.Net.Mail.SmtpClient($SmtpServer, $Port)
if ($UseSSL) {
$smtpClient.EnableSsl = $true
}
if ($psboundparameters.ContainsKey('Credential')) {
$smtpClient.Credentials = $Credential.GetNetworkCredential()
}
$smtpClient.Send($mailMessage)
} catch {
# Return errors as non-terminating
Write-Error -ErrorRecord $_
}
}
#
# Main
#
# This is inserted before the table generated by the script
$PreContent = 'This report was generated because the drive(s) listed below have less than {0} free space. Drives above this threshold will not be listed.' -f ('{0:P2}' -f $Threshold)
# This is a result counter, it'll be incremented for each result which passes the threshold
$i = 0
# Generate the message body. There's not as much error control around WMI as I'd normally like.
$Body = Get-WmiObject Win32_LogicalDisk -Filter 'DriveType=3' -ComputerName $ComputerName | ForEach-Object {
# PSCustomObject requires PS 3 or greater.
# Using Math.Round below means we can still perform numeric comparisons
# Percent free remains as a decimal until the end. Programs like Excel expect percentages as a decimal (0 to 1).
[PSCustomObject]#{
ComputerName = $_.__SERVER
DriveType = $_.DriveType
VolumeName = $_.VolumeName
Name = $_.Name
'Size (GB)' = [Math]::Round(($_.Size / 1GB), 2)
'FreeSpace (GB)' = [Math]::Round(($_.FreeSpace / 1GB), 2)
PercentFree = [Math]::Round(($_.FreeSpace / $_.Size), 2)
}
} | Where-Object {
if ($_.PercentFree -lt $Threshold) {
$true
$i++
}
} | ForEach-Object {
# Make Percentage friendly. P2 adds % for us.
$_.PercentFree = '{0:P2}' -f $_.PercentFree
$_
} | ConvertTo-Html -PreContent $PreContent | Out-String
# If there's one or more warning to send.
if ($i -gt 0) {
$params = #{
To = "ToEmail#Gmail.com"
From = "FromEmail#Gmail.com"
Subject = "Disk Space Storage Report"
Body = $Body
SmtpServer = "smtp.gmail.com"
Port = 587
UseSsl = $true
Credential = $Credential
}
Send-SmtpMessage #params
}
I'm trying to create a powershell script that will alert me when one or more of my certificates are about to expire.I combined some scripts i found on internet and it seems to work fine. The only problem is when sending the email im getting just one big row with all certificate one behind the other. I'd preffer to get more of a list like:
Certificate 1
Subject: CN =hello
Expiration:2/11/2017 1:00:00 AM
Certificate 2
Subject: CN =hello2
Expiration:2/11/2017 1:00:00 AM
If possible i would also like some help on how to just get the CN from the certificate subject rather the the complete subject with (OU, O, L, S,C)
Here is my current script:
import-module webadministration
$DaysToExpiration = 700 #just modify this date for more or less
$expirationDate = (Get-Date).AddDays($DaysToExpiration)
$body = Get-ChildItem CERT:LocalMachine/My |
Where {$_.NotAfter -lt (Get-Date).AddDays($DaysToExpiration)}
$body | select Subject, #{Name="Expiration"; Expression = {$_.NotAfter}} | fl | out-string
$emailSmtpServer = "172.17.1.236"
$emailSmtpServerPort = "25"
$emailSmtpUser = "test"
$emailSmtpPass = "test"
$emailMessage = New-Object System.Net.Mail.MailMessage
$PCName = $env:COMPUTERNAME
$emailMessage.From = "$PCName#test.com"
$emailMessage.To.Add( "test#dev.test.de" )
$emailMessage.Body = $body | select Subject, #{Name="Expiration"; Expression = {$_.NotAfter}} | fl | out-string
$emailMessage.Subject = "Certificates Expiring within $DaysToExpiration days"
$emailMessage.IsBodyHtml = $true
$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort )
$SMTPClient.EnableSsl = $false
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );
if ($emailMessage.Body.Length -gt 1)
{
Write-host "Sending Email"
$SMTPClient.Send( $emailMessage )
}
I was searching for the same and I found the following stack overflow
link
$s = Get-ChildItem -Path 'Cert:\localmachine\My'| select subject
$s -replace "(CN=)(.*?),.*",'$2'
$s = $s -replace "#{Subject="
OR the non regex way ..
$sub = $_.Subject.split(",")[0].split("=")
$sub[1] = $sub[1] -replace "\*","star"
$sub[1]
It is working for most domain certificates but and I can see some issues with self certificates and server certificates.
Either configure $emailMessage.IsBodyHtml = $false or create an HTML body.
I am not from Powershell background.
I am about to schedule task in which a mail is required to send; if disk size is less then expected limit.
Following is script which i am using:
$servers = Get-Content "C:\serverlist.txt";
foreach($server in $servers)
{
# Get fixed drive info
$disks = Get-WmiObject -ComputerName $server -Class Win32_LogicalDisk -Filter "DriveType = 3";
foreach($disk in $disks)
{
$deviceID = $disk.DeviceID;
[float]$size = $disk.Size;
[float]$freespace = $disk.FreeSpace;
#Here you have to mention the drive id for example i mentioned 'C' drive below
if($deviceID -eq "C:")
{
$percentFree = [Math]::Round(($freespace / $size) * 100, 2);
$sizeGB = [Math]::Round($size / 1073741824, 2);
$freeSpaceGB = [Math]::Round($freespace / 1073741824, 2);
if($freeSpaceGB -lt 100)
{
$EmailFrom = "monitoring#mydomainname.no"
$EmailTo = "fatherazrael#evry.com"
$Subject = "Disk Space"
$Body = "$disk drive space is less free space in $server server: $freeSpaceGB"
$SMTPServer = "scan.opinkerfi.is"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
#$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("<From mail ID>", "Password"); //Not Required
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
}
}
}
}
I do not know how to apply logging. Could any one figure out where the problem is? No Logs are there in Event viewer or anywhere.
I am able to configure all this using Event Viewer, Task Scheduler and Performance Tools but i am told to use Powershell.
Your script is working for me. Could it be that your disks are above 100GB space?
if($freeSpaceGB -lt 100)
You could use some error handling. Try to change email sending part to this:
if($freeSpaceGB -lt 1000)
{
try {
$EmailFrom = "monitoring#mydomainname.no"
$EmailTo = "fatherazrael#evry.com"
$Subject = "Disk Space"
$Body = "$disk drive space is less free space in $server server: $freeSpaceGB"
$SMTPServer = "scan.opinkerfi.is"
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)
#$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("<From mail ID>", "Password"); //Not Required
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
}
catch
{
$Error[0].Exception.Message | Out-File ($server + '_error.txt')
}
You will get related errors during email send part to current directory with txt files.