Home > Net >  I have problem getting info from all $Users to mail only get info from 1 machine
I have problem getting info from all $Users to mail only get info from 1 machine

Time:12-17

My problem is I get the list in console showing all machines "Name" , LastLogonDate Description.. But when I run full script only 1 machines info is sent by mail.. What am I missing? Sorry im kinda new to PS.

##Contains my list of computers that I need data from
$Users = 'PCName1', 'PCName2', 'PCName3'
##Gets AdComputer info
$Computers = Get-ADComputer -Filter * -Properties LastLogOnDate, Description

$Users | foreach {

    $User = $_
    $selectedMachine = $Computers | where Name -eq $User
    if ($selectedMachine) {
        $selectedMachine | select Name, LastLogOnDate, Description
    }
    # if it does not exist...
}

[string[]]$recipients = [email protected]
$fromEmail = [email protected]
$server = "IP"
[string]$emailBody = "$Computer"   "Mail Rapport sendt fra task scheduler $computer $time "
send-mailmessage -from $fromEmail -to $recipients -subject "Machines INFO " -body $emailBody -priority High -smtpServer $server

CodePudding user response:

You are not capturing the output from the ForEach-Object loop anywhere, so the info only appears on console.. Furthermore, I can't see where variables $Computer (singular) and $time come from..

Also, I might interest you to make use of Splatting to use on cmdlets that take a lot of parameters like Send-MailMessage.

Try

# Contains my list of computers that I need data from
$Computers = 'PCName1', 'PCName2', 'PCName3'

# loop through the list of computers and capture the output objects in variable $result
$result = foreach ($computer in $Computers) {
    $pc = Get-ADComputer -Filter "Name -eq '$computer'" -Properties LastLogOnDate, Description
    if ($pc) {
        # output the object with the properties you need
        $pc | Select-Object Name, LastLogOnDate, Description
    }
    else {
        Write-Warning "Computer '$computer' not found.."
    }
}

# test if we have something to email about
if (@($result).Count) {
    # join the resulting object array (in this demo as simple Table)
    $body = "Mail Rapport sendt fra task scheduler`r`n{0}"-f ($result | Format-Table -AutoSize | Out-String)

    # use splatting
    $mailProps = @{
        To         = '[email protected]'
        From       = '[email protected]'
        Subject    = 'Machines INFO'
        Body       = $body
        Priority   = 'High'
        SmtpServer = '[email protected]'
        # other parameters can go here
    }
    # send the email
    Send-MailMessage @mailProps
}
  • Related