Hashtable没有在Powershell中正确更新

时间:2013-10-21 13:13:42

标签: powershell hashtable

所以我创建了每周重启脚本。我读了一个AD组,然后在周末重启了一堆电脑。然后我通过电子邮件发送带有日志的HTML结果。我通过在列表中添加几台计算机来测试这一点。它只返回最后的unpingable计算机。有人可以告诉我为什么吗?我需要第二眼。我以前做过这种类型的哈希表,它工作得很好。

$RBList = (Get-QADGroupMember prv_RebootSchedule | Sort Name | Select -expand Name)
foreach($PC in $RBList){
$datetime = Get-Date            
ping -n 2 $PC >$null
if($lastexitcode -eq 0){
shutdown /r /f /m \\$PC /d p:1:1 /t 600 /c "Weekly Reboot - Maintnence scheduled!"
write-host "$pc is rebooting"
$result = "Success"
} else {
Write-host "$pc has error adding to table"
$Result = "Error - Check"
}
$table = [ordered]@{
Workstation = $pc
Result = $result
Time = $datetime
} 
}
$html =  [PSCustomObject]$table | convertto-html -CssUri "C:\scripts\automatedreboot\table.css"         
send-mailmessage -to "email@email.com" -from "Automated Reboot<no-reply@email.com>" -subject "Automated Reboot Error Log" -BodyAsHtml "$html" -smtpserver smtp.email.com

2 个答案:

答案 0 :(得分:2)

尝试这样的事情:

$RBList = (Get-QADGroupMember prv_RebootSchedule | Sort Name | Select -expand Name)
$table = @()

foreach($PC in $RBList)
{
    $obj = "" | select Workstation, Result, Time
    $datetime = Get-Date            
    ping -n 2 $PC >$null
    if($lastexitcode -eq 0)
    {
        #shutdown /r /f /m \\$PC /d p:1:1 /t 600 /c "Weekly Reboot - Maintnence scheduled!"
        write-host "$pc is rebooting"
        $result = "Success"
    } 
    else
    {
        Write-host "$pc has error adding to table"
        $Result = "Error - Check"
    }

$obj.Workstation = $pc
$obj.Result = $result
$obj.Time = $datetime

$table += $obj    
}

$html = $table | convertto-html -Property name, value -as table

答案 1 :(得分:2)

相同的想法(如CB),但实现有点不同:

$RBList = (Get-QADGroupMember prv_RebootSchedule | Sort Name | Select -expand Name)

$EmailParams = @{
 to         = 'email@email.com' 
 from       = 'Automated Reboot<no-reply@email.com>' 
 subject    = 'Automated Reboot Error Log' 
 BodyAsHtml =  $true
 smtpserver = 'smtp.email.com'
 }

$table = 
   foreach($PC in $RBList){
     $datetime = Get-Date            
     ping -n 2 $PC >$null

     if($lastexitcode -eq 0){
       shutdown /r /f /m \\$PC /d p:1:1 /t 600 /c "Weekly Reboot - Maintnence scheduled!"
       write-host "$pc is rebooting"
       $result = "Success"

       } else {
         Write-host "$pc has error adding to table"
         $Result = "Error - Check"
       }

   [PSCustomObject]@{
                      Workstation = $pc
                      Result      = $result
                      Time        = $datetime
                     } 
  } 

$html = $table | convertto-html -CssUri "C:\scripts\automatedreboot\table.css"


Send-MailMessage @EmailParams -Body $html