【问题标题】:I have problem getting info from all $Users to mail only get info from 1 machine我从所有 $Users 获取信息到邮件时遇到问题,只能从 1 台机器获取信息
【发布时间】:2022-01-19 11:52:26
【问题描述】:

我的问题是我在控制台中获得了显示所有机器“名称”、LastLogonDate 描述的列表。但是当我运行完整脚本时,只有 1 台机器信息通过邮件发送。我错过了什么?抱歉,我对 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 = mymail@asds.com
$fromEmail = from@email.com
$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

【问题讨论】:

  • 欢迎来到 StackOverflow!你好像忘了问一个问题。请update your post 详细说明代码应该做什么、它当前在做什么以及您需要什么帮助。

标签: powershell active-directory


【解决方案1】:

您没有在任何地方捕获 ForEach-Object 循环的输出,因此该信息仅出现在控制台上。 此外,我看不到变量$Computer(单数)和$time来自哪里..

另外,我可能有兴趣让您使用Splatting 来使用带有大量参数(如 Send-MailMessage)的 cmdlet。

试试

# 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         = 'mymail@asds.com'
        From       = 'from@email.com'
        Subject    = 'Machines INFO'
        Body       = $body
        Priority   = 'High'
        SmtpServer = 'mailserver@yourdomain.com'
        # other parameters can go here
    }
    # send the email
    Send-MailMessage @mailProps
}

【讨论】:

  • 谢谢西奥,这成功了!
猜你喜欢
  • 2021-05-19
  • 1970-01-01
  • 1970-01-01
  • 2013-02-20
  • 1970-01-01
  • 2010-12-21
  • 2019-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多