Leverage Get-Help to understand what is expected for the parameter:
Get-Help Send-MailMessage -Full
PARAMETERS
-Attachments
Specifies the path and file names of files to be attached to the email message. You can use this parameter or pipe the paths and file names to Send-MailMessage .
Required? false
Position? named
Default value None
Accept pipeline input? True (ByValue)
Accept wildcard characters? false
The String indicates a string array, specifically an array of paths. If you run your command:
It is returning an object, so you need to get a Property of that object, which is FullName. Additionally, if you look at about_Splatting, you can make the code much cleaner:
$File = (Get-ChildItem -Path C:\Scripts | Select -ExpandProperty FullName -Last 1)
$mailParams = @{
From = "adcb@gmail.com"
To = "efgh@gmail.com"
Attachment = $File
Subject = "Here's the Email Subject"
Body = "This is what I want to say"
SMTPServer = "smtp.gmail.com"
}
Send-MailMessage @mailParams
I believe the issue is with your file variable. You have double quotes around the entire command. Use the -LiteralPath parameter with double quotes around the value if necessary. As it is now, $file is nothing more than a PowerShell command saved as a string. I think the -attatchment parameter probably wants a full path to a file? Not in front of a computer right now so can’t confirm. But your file variable stood out to me as a likely issue.