PScredential question

I have a script that sends monthly AD reports as an SMTP attachment. I’ve specified the username, and the password is stored locally in a text file on my desktop, but a Credentials box still pops up. The script works perfectly as long as I provide the username/password in the credential box.

(Get-Credential).password | ConvertFrom-SecureString > password.txt
$pw = Get-Content .\password.txt | ConvertTo-SecureString
$cred = New-Object System.Management.Automation.PSCredential “Myuser”, $pw
Send-MailMessage -SmtpServer -Port 587 -Credential $cred -to “” -attachments “C:\users\myuser\desktop\activedirectoryreport.xlsx” -from “” -Subject “Monthly AD Report for $date” -body “Test for Send-MailMessage”>

Separate question - I want add the date to the Subject line using . I thought I could do $date = (Get-Date).AddDays(-1).ToString(‘MM-dd-yyyy’), and pass $date into the subject line, but that isn’t working. Any suggestions?

Can you try this and see if it works?

Run this once only :

$credentials = Get-Credential
$credentials | Export-CliXML cred.xml

Then for your monthly recurring script

$cred = Import-CliXML cred.xml
Send-MailMessage -SmtpServer -Port 587 -Credential $cred -to "" -attachments "C:\users\myuser\desktop\activedirectoryreport.xlsx" -from "" -Subject "Monthly AD Report for $date" -body "Test for Send-MailMessage"

That worked perfectly! Thank you very much.