Forum Discussion

eli_sorow's avatar
eli_sorow
Copper Contributor
Nov 25, 2020
Solved

send powershell script output by email

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 mailto: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

 

  • You 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"
    }

10 Replies

  • 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.

    • eli_sorow's avatar
      eli_sorow
      Copper Contributor

      VasilMichev 

       

      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

      • VasilMichev's avatar
        VasilMichev
        MVP

        You 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"
        }

Resources