# This script will take an input value from the user and send an email with attachments
# if the attachment filenames match names derived from the input value.
# Load SMO extension (This line might be vestigial if not interacting with SQL Server Management Objects,
# but it's kept as per the original request. It's typically used for SQL Server administration tasks.)
[void][Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
# --- Get User Input ---
# Define the title for the input box
$title = 'Email My Scripts'
# Define the message prompt for the user
$msg = 'Enter your INPUT :'
# Display an input box to the user and store their response
$INPUTVALUEvers = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title)
# Replace any backslashes in the input value with underscores for use in filenames
$INPUTVALUE = $INPUTVALUEvers -replace '\\','_'
# --- Define Email Variables ---
# Sender email address
$fromaddress = "xyz@gmail.com"
# Recipient email address
$toaddress = "xyz@gmail.com"
# Email subject line, incorporating the user's original input value
$Subject = "My report $INPUTVALUEvers"
# Email body content
$body = "My reports"
# SMTP server address for sending emails
$smtpserver = "my.com.au"
# Display the processed input value (with backslashes replaced) to the console
write-host $INPUTVALUE
# --- Prepare Attachments ---
# Define the path where the attachment files are located
$attachmentPath = "\\My_path\My\"
# Construct the filenames for the attachments based on the processed input value
$attachment1 = "MyReport_$INPUTVALUE.html"
$attachment2 = "Mylogon_$INPUTVALUE.txt"
# Get the full path to the attachment files.
# Get-ChildItem is used to find the files in the specified path that match the include patterns.
# The result is cast to an array to ensure it's treated as a collection, even if only one file is found.
[array]$attachments = Get-ChildItem -Path $attachmentPath -Include $attachment1, $attachment2
# --- Send Email ---
# Create a hashtable of parameters for the Send-MailMessage cmdlet.
# This makes the command more readable and manageable.
$Msg = @{
To = $toaddress
From = $fromaddress
Body = $body
Subject = $Subject
SmtpServer = $smtpserver
BodyAsHtml = $True # Indicates that the email body contains HTML content
Attachments = $attachments.FullName # Pass the full paths of the found attachments
}
# Send the email using the defined parameters.
# The '@Msg' syntax is called splatting, which passes the hashtable keys as parameters to the cmdlet.
Send-MailMessage @Msg
No comments:
Post a Comment