I created the following script to check for the appearance of AVHDX files and send an appropriate email.
#AVHDX file location(s)
$file1 = "C:\*.avhdx"
$file2 = "C:\*.avhdx"
#Check for Existence of AVHDX files
$file1Exists = Test-Path $file1
$file2Exists = Test-Path $file2
#Email Settings
$cred = Get-StoredCredential -Target "M365SMTPCred"
$avhdxyes = "There are Orphaned AVHDX files found. Please clean up and merge immediately!"
$avhdxno = "There are no orphaned AVHDX files."
$subavhdxyes = "Errors - AVHDX Files found - Company"
$subavhdxno = "No AVHDX Files - Company"
If ($file1Exists -or $file2Exists)
{
Send-MailMessage -To "somebody@somebody.com" -from "somebody@somebody.com" -Subject $subavhdxyes -Body $avhdxyes -BodyAsHtml -smtpserver smtp.office365.com -usessl -Credential $cred -Port 587
}
Else
{
Send-MailMessage -To "somebody@somebody.com" -from "somebody@somebody.com" -Subject $subavhdxno -Body $avhdxno -BodyAsHtml -smtpserver smtp.office365.com -usessl -Credential $cred -Port 587
}
Microsoft 365 app password credentials were inserted via "new-storedcredential -target "M365SMTPCred" -username "myM365username" -password "pwd"" using the local/builtin Administrator account (non domain server). This is the SAME account that is scheduled to run the task.
Script runs OK directly from powershell, or with "run only with user logged on", but if I try to automate and "run whether user is logged on or not" it gets stuck at "Running"...
If I add some transcript logging, I get the following:
PS>TerminatingError(Send-MailMessage): "Cannot validate argument on parameter 'Credential'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again."
Send-MailMessage : Cannot validate argument on parameter 'Credential'. The argument is null or empty. Provide an
argument that is not null or empty, and then try the command again.
At C:\PowerShell\avhdxcheck.ps1:34 char:187
- ... Html -smtpserver smtp.office365.com -usessl -Credential $cred -Port 5 ...
- ~~~~~
- CategoryInfo : InvalidData: (:) [Send-MailMessage], ParameterBindingValidationException
- FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.SendMailMessage
Send-MailMessage : Cannot validate argument on parameter 'Credential'. The argument is null or
empty. Provide an argument that is not null or empty, and then try the command again.
At C:\PowerShell\avhdxcheck.ps1:34 char:187
- ... Html -smtpserver smtp.office365.com -usessl -Credential $cred -Port 5 ...
- ~~~~~
- CategoryInfo : InvalidData: (:) [Send-MailMessage], ParameterBindingValidationExce
ption
- FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.Send
MailMessage
What am I doing wrong?!? Thanks in advance!