Power Shell: If condition variable comparison not working - powershell

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) {
<# ... #>
}

Related

Powershell scripts to send multiple attachements as HTML format

I have prepared the below scripts to send multiple files as HTML format (not as attachments). But it is adding the company disclaimer within the table of 1st report while sending email.
[No issue with 2nd report].
############ START ############
$report = "C:\Reports\ADReport16.htm"
$report1 = "C:\Reports\ADReport26.htm"
$BodyReport1 = Get-Content "$report" -Raw
$BodyReport2 = Get-Content "$report1" -Raw
$BodyReport1 += $BodyReport2
Send-MailMessage -SmtpServer '10.10.10.10' -From 'AD.REPORT#microsoft.com' -To 'xxx.zzz#cisco.net' -Subject "Active Directory Health Report" -Body $BodyReport1 -BodyAsHtml
############ END ############
After reproducing from my end, I could able to make this work by setting IsBodyHtml to $true Below is the complete script that worked for me.
$report = "Report1.html"
$report1 = "Report2.html"
$BodyReport1 = Get-Content "$report" -Raw
$BodyReport2 = Get-Content "$report1" -Raw
$BodyReport1 += $BodyReport2
$emailPassword = "<PASSWORD>"
$emailCredential = New-Object System.Net.NetworkCredential("<EMAIL>", $emailPassword)
$smtpServer = "smtp.office365.com"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Port = 587
$smtp.EnableSSl = $true
$smtp.Credentials = $emailCredential
$messageObject = new-object Net.Mail.MailMessage
$messageObject.IsBodyHtml = $true
$messageObject.From = "<FROM>"
$messageObject.To.add("<TO>")
$msg.subject = "<SAMPLE_SUBJECT>"
$msg.body = $BodyReport1
$smtp.Send($msg)
RESULTS:

Powershell RDS CAL email Report

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)

How to compare 2 text files using powershell

I want to be able compare the contents of 2 text files and see if the contents of those files are the same. If the contents of the 2 files are different, I need this powershell script to send me an email with a list of differences from the 2 files. Here is my code:
$fromaddress = "noreply#xy.com"
$toaddress = "me#xy.com "
$Subject = "Comparing 2 text files"
$login = "abc"
$password = "12345" | Convertto-SecureString -AsPlainText -Force
$smtpserver = "smtp.office.com"
$message = new-object System.Net.Mail.MailMessage
$message.From = $fromaddress
$message.To.Add($toaddress)
$message.IsBodyHtml = $True
$message.Subject = $Subject
$attach = new-object Net.Mail.Attachment($attachment)
$message.Attachments.Add($attach)
$message.body = $body
$message.Priority = [System.Net.Mail.MailPriority]::High
$smtp = new-object Net.Mail.SmtpClient($smtpserver, 587)
$smtp.EnableSsl = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($login, $password);
IF (Compare-Object -ReferenceObject (Get-Content $dir\file1.txt) -DifferenceObject (Get-Content $dir\file2.txt)){
Write-Output "The files are different "
$smtp.Send($message);
}
Else {
Write-Output "The files are not different"
}
I have looked at different online resources that suggested the use of Compare-Object cmdlet but it doesn't seem to work in my situation. The problem with my code is that, its returning everything from file1. Any one who knows why this is not working for me?
To compare two file and determine if they are identical use a file hash:
$hash1 = Get-FileHash $dir\file1.txt
$hash2 = Get-FileHash $dir\file2.txt
if($hash1 -eq $hash2){
'They are the same'
}else{
'They are NOT the same
}
This scans the 2 text files for differences and pipes it to a third File
$File1 = "C:\Scripts\Txt1.txt"
$File2 = "C:\Scripts\Txt2.txt"
$Location = "C:\Scripts\Txt3.txt"
compare-object (get-content $File1) (get-content $File2) | format-list | Out-File $Location
Output:
You're almost right with your initial script. You just need to add -IncludeEqual
See below. Text files 1 & 2 are just "hi there." Text file 3 is "hi there2"
$1 = gc 'H:\Skype Migrations\file1.txt'
$2 = gc 'H:\Skype Migrations\file2.txt'
$3 = gc 'H:\Skype Migrations\file3.txt'
IF ( ( Compare-Object -ReferenceObject $1 -DifferenceObject $3 -IncludeEqual ).sideindicator -ne "==" )
{ Write-Output "The files are different " }
Else
{ Write-Output "The files are not different" }
Edited to showcase how to use the IncludeEqual

Sending mail Power Shell 4

Good Day! Help please, use this script here:
$file = "C:\Reports\Log_1.txt"
$FileExists = Test-Path $file
If ($FileExists -eq "False") {
Write-Host "sending mail"
$mail = New-Object System.Net.Mail.MailMessage
$mail.From = New-Object System.Net.Mail.MailAddress("test#gmail.com")
$mail.To.Add("test#gmail.com")
$mail.Subject = "report";
$mail.Body = get-content $file
$smtp = New-Object System.Net.Mail.SmtpClient
$smtp.host = "smtp.domen.com"
$smtp.port="25"
$Credentials = new-object System.Net.networkCredential
$Credentials.domain = "smtp.domen.com"
$Credentials.UserName = "test#gmail.com"
$Credentials.Password = "rgrthbdgfhytju"
$smtp.Credentials = $Credentials
$smtp.Send($mail)
}
# else {
#Write-Host "File $file not found"
#}
I get two errors trying to connect the two mail servers.
In the first case, the connection error and the second authentication error:
error 1 (gmail.com): Exception calling with this 1 argument This operation has timed out.
error 2 (corporate post): Exception calling with this 1 argument Failure sending mail.
Sorry,I can not insert a picture of the limitations.

Adding Get-WMI Data To E-mail Body

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)