Mark Minasi's Tech Forum
Sign up Calendar Latest Topics
 
 
 


Reply
  Author   Comment  
wobble_wobble

Avatar / Picture

Associate Troublemaker Apprentice
Registered:
Posts: 940
Reply with quote  #1 
OK script to gather the .gz files add them to an email and mail the report to the necessary accounts.
Not pretty I know, but I have to start somewhere.
This is has extra lines in it as I reuse similar code in different places and until I figure out how to use a repository properly, I rem out lines I don't need.

How can I make it better/ more efficient.

# Script to report on backups of the Test Lab
# Script gathers the list of files, adds it to a file and emails it.
#
# Get the tar.gz file list
Get-ChildItem \\localhost\x$\*.tar.gz -recurse >>D:\Scripts\TestLab\BackupLog.txt
# File cleanup to remove break line
# https://blogs.technet.microsoft.com/heyscriptingguy/2010/07/27/deleting-extra-returns-and-line-feeds-from-a-text-file-using-windows-powershell/
# I'm cleaning up the line spaces in the text file to reduce the amount of line breaks in the email body.
#    Copy the text file.
#    Read the text file.
#    Find lines with text while ignoring blank lines.
#    Remove the blank lines from the text.
#    Write the revised text to a new file.
#    Save the new file with the name of the original text file
Copy-Item -Path D:\Scripts\TestLab\BackupLog.txt D:\Scripts\TestLab\BackupLogCopy.txt
Select-String -Pattern "\w" -Path D:\Scripts\TestLab\BackupLogCopy.txt
Select-String -Pattern "\w" -Path D:\Scripts\TestLab\BackupLogCopy.txt | ForEach-Object { $_.line 
} | Set-Content -Path D:\Scripts\TestLab\BackupLogCopy1.txt

#Connection Details
$username=”Jmcglynn@ireland.ie”
$password=”xxxxyyyyzzzz”
$smtpServer = “172.16.1.13”
$msg = new-object Net.Mail.MailMessage
#Change port number for SSL to 587
$smtp = New-Object Net.Mail.SmtpClient($SmtpServer, 25) 
#Uncomment Next line for SSL  
#$smtp.EnableSsl = $true
# Credentials not needed
#$smtp.Credentials = New-Object System.Net.NetworkCredential( $username, $password )
#From Address
$msg.From = "Rep01-TestLab@ireland.ie"
#To Address, Copy the below line for multiple recipients
$msg.To.Add(“jmcglynn@ireland.ie”)
$msg.To.Add(“VMWare@ireland.ie”)
#Write all data into one email file
d:
cd D:\Scripts\TestLab\
Get-Content topofbody.txt | Add-Content email.txt
Get-Content BackupLogCopy1.txt | Add-Content email.txt
Get-content endofbody.txt | Add-Content email.txt
#Message Body
#$msg.Body=”MJ Flood Ireland Test Lab Backup”
$msg.Body= Get-Content -Path D:\Scripts\TestLab\email.txt -Raw
#Message Subject
$msg.Subject = “Backup report for the Test Lab from Rep01”
#your file location
#$files=Get-ChildItem “C:\scripts\Output”
#Foreach($file in $files)
#{
Write-Host “Attaching File :- ” $file
$attachment = New-Object System.Net.Mail.Attachment –ArgumentList D:\Scripts\TestLab\BackupLog.txt
$msg.Attachments.Add($attachment)
#}
$smtp.Send($msg)
$attachment.Dispose();
$msg.Dispose();
# Clean out the email files and text content
d:
cd d:
cd D:\Scripts\TestLab\
del email.txt
del backup*.txt

# Move files to archive
<#
d:
cd d:
cd X:\TestLabArchive
$date = (Get-Date -f dd_MM_yyyy)
md $date
# Copy the archive files to an archive folder
$GZFolder =  "X:\TestLabBackup\" 
$ArchiveFolder = "X:\TestLabArchive\$date" 
copy-Item $GZFolder $ArchiveFolder
Move-Item $ZipFolder\*.gz $ArchiveFolder
#>

__________________
Have you tried turning it off and walking away? The next person can fix it!

New to the forum? Read this
0
cj_berlin

Avatar / Picture

Senior Member
Registered:
Posts: 431
Reply with quote  #2 
Here's to report generation:

$path = "\\localhost\x$"
$filter = "*.tar.gz"
$outfile = "d:\scripts\testlab\file_report.log"
$archiveroot = "x:\testlabarchive"

$lines = @()
Get-ChildItem -Path $path -Filter $filter -Recurse | foreach {
    $lines += $_.FullName
}
$lines | Set-Content $outfile -Encoding UTF8


As to sending mail, I prefer Send-MailMessage for its simplicity, especially in handling attachments (just pass an array of file names or a single file name).

Archiving the log file,

$date =Get-Date -Format "dd_MM_yyyy"
if (!(Test-Path "$archiveroot\$date")) {
   New-Item -Path "$archiveroot" -Name $date -ItemType Folder
}
try {
    Move-Item $outfile -Destination "$archiveroot\$date"
} catch {
    Write-Host "Error moving $outfile to $archiveroot\$date"
}



HTH

__________________
Evgenij Smirnov

MVP Cloud & Datacenter Management
My personal blog (German): http://www.it-pro-berlin.de/
My stuff on PSGallery: https://www.powershellgallery.com/profiles/it-pro-berlin.de/
0
jsclmedave

Administrator
Registered:
Posts: 506
Reply with quote  #3 
I use this method for Email -

Note Im clipping out the parameters being set and just showing the Email Bits...



# Email Notice of Reports with attachments
$Subject = "EXPORT for DomainA & DomainB Summary $Date"    # Set Earlier in Script
$TO = "timbolton@BigDog.com"
$Attachments = $SomeJobCopyLogfile,$SomeJobScriptLogfile   # Set Earlier in Script
$SMTPServer = "BigDog.com"
$SMTPPort = "25"

$Body = @"
Hello,
Job for DomainA & DomainB Summary $Date has completed.  
See attached log file $Date SomeJob.log for details and to check for any Errors.
DomainA & DomainB: $DestRVTOOLS
 
-----------------------------------------------------------------------------
If you have any questions please contact Tools & Automation at Email:  SomeGuy@BigDog.com
PLEASE DO NOT REPLY TO THIS EMAIL. REPLIES TO THIS ADDRESS ARE ROUTED TO AN UNMONITORED MAILBOX.
-----------------------------------------------------------------------------
"@
$Email = @{
From = "SomeGuy@BigDog.com"
To = $TO   # Set Earlier in Script
#Cc = 
#Bcc = "$MyEmail"  # Set Earlier in Script
Subject = "$Subject"  # Set Earlier in Script
Body = "$Body"  # Set Earlier in Script
SMTPServer = "BigDog.com"
Attachments = $Attachments   # Set Earlier in Script
}
Send-MailMessage @Email






This is what I use to test SMTP functionality from a specific Server.

I added some Servers to the allowed list granting rights for those servers to send Email via PowerShell using the Email Frame Relay.

 

Once the Requests were completed, I was able to test from the Target Servers using PowerShell.

 

1)      Open a PowerShell Session on the Target Server.

2)      Copy and Paste this code into the PowerShell Session and Enter.

 

 



$PSEmailServer = "Relay.BigDog.com"   # The Relay Name Would Go Here
$Subject = "Testing Email Relay on Server $Env:COMPUTERNAME"
$Body = @"

Give a man a script; 
    feed him for a Get-Date. 
`r`n
Teach a man to script; 
    feed him for a New-TimeSpan.
`r`n 
                Lao Tzu, 4th century BC
`r`n 
-------------------------------------------------------------
                PLEASE DO NOT REPLY TO THIS EMAIL.
REPLIES TO THIS ADDRESS ARE ROUTED TO AN UNMONITORED MAILBOX.
-------------------------------------------------------------
"@

$Email = @{
From = "DONOTREPLY@$Env:COMPUTERNAME"
To = "John.Doe@BigDog.com","jane.Doe@BigDog.com","Some.Guy@BigDog.com"
Cc = "Tim.Bolton@BigDog.com"
#Bcc = "Tim.Bolton@BigDog.com"
Subject = "$Subject"
Body = "$Body"
}
Send-MailMessage @Email


 

3)      The recipients listed (TO & CC) will receive the email message if the Email Relay has been configured to allow the Target Server.





__________________
Tim Bolton @jsclmedave
Email: [string](0..20|%{[char][int](32+('527377347976847978324785847679797514357977').substring(($_*2),2))}) -replace ' '  

New to the forum? Please Read this
0
Infradeploy

Avatar / Picture

Senior Member
Registered:
Posts: 186
Reply with quote  #4 
Never ever use relative paths in a script

$archivefolder = "X:\TestLabArchive\$(Get-Date -f dd_MM_yyyy)"
if (!(test-path)){
new-item archivefolder -ItemType container
}
# Copy the archive files to an archive folder
$GZFolder = "X:\TestLabBackup\"
copy-Item $GZFolder $ArchiveFolder
Move-Item $ZipFolder\*.gz $ArchiveFolder



__________________
Have SpaceSuit, Will Travel

0
jsclmedave

Administrator
Registered:
Posts: 506
Reply with quote  #5 
Quote:
Originally Posted by Infradeploy
Never ever use relative paths in a script

$archivefolder = "X:\TestLabArchive\$(Get-Date -f dd_MM_yyyy)" if (!(test-path)){ new-item archivefolder -ItemType container } # Copy the archive files to an archive folder $GZFolder = "X:\TestLabBackup\" copy-Item $GZFolder $ArchiveFolder Move-Item $ZipFolder\*.gz $ArchiveFolder



Why not..?  I'm setting it at the time the script is being ran.  Is this just a poor practice in case the scripts runs over night or something?

I don't understand why it's an issue...

__________________
Tim Bolton @jsclmedave
Email: [string](0..20|%{[char][int](32+('527377347976847978324785847679797514357977').substring(($_*2),2))}) -replace ' '  

New to the forum? Please Read this
0
wobble_wobble

Avatar / Picture

Associate Troublemaker Apprentice
Registered:
Posts: 940
Reply with quote  #6 
Quote:
Originally Posted by cj_berlin


Archiving the log file,

$date =Get-Date-Format "dd_MM_yyyy" if (!(Test-Path "$archiveroot\$date")) { New-Item -Path "$archiveroot" -Name $date -ItemType Folder } try { Move-Item $outfile -Destination  "$archiveroot\$date" } catch { Write-Host "Error moving $outfile to $archiveroot\$date" } 


HTH


First bit worked a charm, thanks.

Found a small change in the above part.
Should be
-ItemType Directory
not
-ItemType Folder


__________________
Have you tried turning it off and walking away? The next person can fix it!

New to the forum? Read this
0
wobble_wobble

Avatar / Picture

Associate Troublemaker Apprentice
Registered:
Posts: 940
Reply with quote  #7 
Curious about Tims question.


__________________
Have you tried turning it off and walking away? The next person can fix it!

New to the forum? Read this
0
Infradeploy

Avatar / Picture

Senior Member
Registered:
Posts: 186
Reply with quote  #8 
Is poor practise, when something changes because of some reason you wind up where it doesn't suppose to go.
I've seen while disks wiped because they want to get rid of a temp folder and had relative paths

__________________
Have SpaceSuit, Will Travel

0
jsclmedave

Administrator
Registered:
Posts: 506
Reply with quote  #9 
Quote:
Originally Posted by Infradeploy
Is poor practise, when something changes because of some reason you wind up where it doesn't suppose to go. I've seen while disks wiped because they want to get rid of a temp folder and had relative paths


However,, this is for a specific purpose only THEY asked for it so,,,  


So are you saying that you would copy and paste my script to delete file or HD Space? WOW!!!  Mr Robot want's to,,, HAS met you...  : ) 

P.S. 
 F)#(&@*GFB!Z HATE EDGE!!!  This took me over 20 min's to edit........

__________________
Tim Bolton @jsclmedave
Email: [string](0..20|%{[char][int](32+('527377347976847978324785847679797514357977').substring(($_*2),2))}) -replace ' '  

New to the forum? Please Read this
0
wobble_wobble

Avatar / Picture

Associate Troublemaker Apprentice
Registered:
Posts: 940
Reply with quote  #10 
Quote:
Originally Posted by jsclmedave


 F)#(&@*GFB!Z HATE EDGE!!!  This took me over 20 min's to edit........


20 minutes you'll never get back


__________________
Have you tried turning it off and walking away? The next person can fix it!

New to the forum? Read this
0
jsclmedave

Administrator
Registered:
Posts: 506
Reply with quote  #11 
Quote:
Originally Posted by Infradeploy
Is poor practise, when something changes because of some reason you wind up where it doesn't suppose to go. I've seen while disks wiped because they want to get rid of a temp folder and had relative paths


AH!  relative Paths...  Ok I understand what you mean now...

__________________
Tim Bolton @jsclmedave
Email: [string](0..20|%{[char][int](32+('527377347976847978324785847679797514357977').substring(($_*2),2))}) -replace ' '  

New to the forum? Please Read this
0
Previous Topic | Next Topic
Print
Reply

Quick Navigation:

Easily create a Forum Website with Website Toolbox.