Nov 25 2020 07:16 AM
Hi all,
i'm trying to send the output of a powershell script by mail.
here's the script : collect o365 unused licenses and send the result by mail
$licenses = Get-MsolAccountSku
foreach ($license in $licenses){
$UnusedUnits = $license.ActiveUnits - $license.ConsumedUnits
$output = "$($license.SkuPartNumber) has $unusedUnits unused licenses" | Out-String
}
Send-MailMessage -From sender@email.com -To receptient@email.com -Subject licenses_left -Body $output -SmtpServer 'smtp.office365.com' -Port '587' -UseSsl -Credential sender@email.com
it's working, i receive the mail except in the body i have only one line, the last result:
O365_BUSINESS has -2 unused licenses
instead of something like :
TREAM has 999999 unused licenses
SPZA_IW has 9999 unused licenses
WINDOWS_STORE has 0 unused licenses
FLOW_FREE has 9829 unused licenses
O365_BUSINESS has -2 unused licenses
anyone has an idea of what i'm doing wrong ?
thanks ll for your help
KR
Eli
Nov 25 2020 08:49 AM
Well you are overwriting your $output variable on each iteration. Instead, you should add to it, or use a list, or whichever other method you prefer.
Nov 25 2020 09:02 AM
thank you very much for your answer wich i m sorry is not obsvious for me.
i don't see how to add it instead.
i'm trying to keep this script simple without any file insertion.
thanks for your help
Nov 25 2020 11:49 PM
SolutionYou can do something like this:
$output = @()
$licenses = Get-MsolAccountSku
foreach ($license in $licenses){
$UnusedUnits = $license.ActiveUnits - $license.ConsumedUnits
$output += "$($license.SkuPartNumber) has $unusedUnits unused licenses"
}
Nov 26 2020 12:50 AM
Hi,
the send-mailMessage comand doesn't like the "+" parameter in $output +=
and when i remove it , i have got the same result (only one line)
Nov 26 2020 08:38 AM
You dont need to change that cmdlet, just replace the stuff I posted above.
Nov 26 2020 08:42 AM - edited Nov 26 2020 08:42 AM
Oh wait, seems I forgot the stringify part... Replace it with
($output | Out-String)
Nov 27 2020 06:52 AM
yes thx was already done but
because of the output syntaxt : $output += email is not sent
Nov 27 2020 11:33 AM
Hi
@eli_sorow , as @Vasil Michev wrote, copy his code and in the Send-Message cmdlet you will need to make this small change
-Body ($output | Out-String) instead of -Body $output
Dec 01 2020 02:22 AM
it's working fine.
thank you both for your help and time, much appreciated!
KR
Eli
Dec 01 2020 02:37 AM