如何在PowerShell中整合控制台输出并以HTML格式的电子邮件发送

时间:2019-02-10 12:19:51

标签: windows powershell scripting

祝你好运

我正在尝试改编this script(最初由Sitaram Pamarthi撰写),其主要目的是在我拥有的Windows系统上自动执行日常的管理本地管理员密码的管理任务。我的控制权。到目前为止,该脚本可以正常工作-因为我可以更改密码并获取电子邮件输出(尽管是文本格式)-但还不足够。

这是我脚本的摘录:

完整上下文的脚本为available here

$Computers = Get-Content -Path $InputFile

#Now let's loop through each computer and change the specified account password.
ForEach ($Computer in $Computers) {

    $Computer   =   $Computer.ToUpper()
    $IsOnline   =   "OFFLINE"
    $Status     =   "SUCCESS"

    Write-Verbose "Working on $Computer"
    If((Test-Connection -ComputerName $Computer -count 1 -ErrorAction 0)) {
        $IsOnline = "ONLINE"
        Write-Verbose "`t$Computer is Online"
    } Else { Write-Verbose "`t$Computer is OFFLINE" }

    Try {
        $Account = [ADSI]("WinNT://$Computer/$TargetAccount,user")
        $Account.psbase.invoke("setpassword",$Pwd1_Text)
        Write-Verbose "`tPassword Change completed successfully"
    }
    Catch {
        $Status = "FAILED"
        Write-Verbose "`tFailed to Change the password for $TargetAccount on $Computer. Error: $_"
        $StatsError = "$_"
    }

    $Obj = New-Object -TypeName PSObject -Property @{
        Date = "$(Get-Date)"
        ComputerName = $Computer
        IsOnline = $IsOnline
        PasswordChangeStatus = $Status
        DetailedStatus = $StatsError
    }

    $Obj | Format-Table ComputerName, Date, IsOnline, PasswordChangeStatus, DetailedStatus -AutoSize
    $Obj | Select-Object "ComputerName", "Date", "IsOnline", "PasswordChangeStatus", "DetailedStatus" | Export-Csv -Append -Path ".\output.csv" -NoTypeInformation

    If($Status -eq "FAILED" -or $IsOnline -eq "OFFLINE") {
        $Stream.Writeline("$Computer `t $IsOnline `t $Status")
    }
}

#Finally, let's close the Stream Writer, write the stream to the text file
#and notify the user of the location of the FailedComputers log file
$Stream.Close()
Write-Host "`n`nFailed computers list is saved to $FailedComputers"
$ScriptEndDate = $(Get-Date)

#Send an email log of what was done
$MsgBody = @"

Dear IT Admins,

Please be advised that the local admin account password for [ $TargetAccount ] has been changed
successfully on the following hosts:

Action Initiated by:  `t$([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)
Script Started:  `t$ScriptStartDate
Script Ended:  `t$ScriptEndDate

"@
Send-MailMessage -Body $MsgBody -Verbose

# Finally, let's clear the default parameters we set earlier
$PSDefaultParameterValues.Clear()

#END SCRIPT

该脚本当前输出到PowerShell控制台,如下所示:

ComputerName Date                IsOnline PasswordChangeStatus DetailedStatus
------------ ----                -------- -------------------- --------------
HOME2        02/10/2019 06:18:20 ONLINE   FAILED               Exception calling "Invoke" with "2" argument(s): "Access is denied....



ComputerName Date                IsOnline PasswordChangeStatus DetailedStatus
------------ ----                -------- -------------------- --------------
HOME3        02/10/2019 06:18:22 ONLINE   FAILED               Exception calling "Invoke" with "2" argument(s): "Access is denied....



ComputerName Date                IsOnline PasswordChangeStatus DetailedStatus
------------ ----                -------- -------------------- --------------
HOME4        02/10/2019 06:18:29 OFFLINE  FAILED               Exception calling "Invoke" with "2" argument(s): "The network path was not found....

我的问题-如何使我的脚本合并输出,如下所示(对于ONLINE和OFFLINE主机都只有一个标题行),以便可以将其包含在电子邮件正文中?

ComputerName Date                IsOnline PasswordChangeStatus DetailedStatus
------------ ----                -------- -------------------- --------------
HOME2        02/10/2019 06:18:20 ONLINE   FAILED               Exception calling "Invoke" with "2" argument(s): "Access is denied....
HOME3        02/10/2019 06:18:22 ONLINE   FAILED               Exception calling "Invoke" with "2" argument(s): "Access is denied....
HOME4        02/10/2019 06:18:29 OFFLINE  FAILED               Exception calling "Invoke" with "2" argument(s): "The network path was not found....

我相信我可能必须以某种方式将控制台输出转换为表,然后将CSS包含在可以传递给Send-MailMessage cmdlet的标头变量中,以便对电子邮件应用某些样式。但是我还没有弄清楚如何做到这一点,因此非常感谢您对该平台的任何帮助。

谢谢大家!

1 个答案:

答案 0 :(得分:1)

游戏晚了一点,但是我想说您应该将所有PSObjects收集/存储在ArrayList中,然后应用Format-Table。此示例按预期方式工作-我只是在测试计算机是否在线,并注释了您的更改密码。

$Computers = @('SERVERA', 'SERVERB')

[System.Collections.ArrayList] $res = New-Object -TypeName "System.Collections.ArrayList"

#Now let's loop through each computer and change the specified account password.
ForEach ($Computer in $Computers) {

    $Computer   =   $Computer.ToUpper()
    $IsOnline   =   "OFFLINE"
    $Status     =   "SUCCESS"

    Write-Verbose "Working on $Computer"
    If((Test-Connection -ComputerName $Computer -count 1 -ErrorAction 0)) {
        $IsOnline = "ONLINE"
        Write-Verbose "`t$Computer is Online"
    } Else { Write-Verbose "`t$Computer is OFFLINE" }

    <#
    Try {
        $Account = [ADSI]("WinNT://$Computer/$TargetAccount,user")
        $Account.psbase.invoke("setpassword",$Pwd1_Text)
        Write-Verbose "`tPassword Change completed successfully"
    }
    Catch {
        $Status = "FAILED"
        Write-Verbose "`tFailed to Change the password for $TargetAccount on $Computer. Error: $_"
        $StatsError = "$_"
    }
    #>

    $Obj = New-Object -TypeName PSObject -Property @{
        Date = "$(Get-Date)"
        ComputerName = $Computer
        IsOnline = $IsOnline
        PasswordChangeStatus = $Status
        DetailedStatus = $StatsError
    }

    $res.Add($Obj)

    #$Obj | Format-Table ComputerName, Date, IsOnline, PasswordChangeStatus, DetailedStatus -AutoSize
    #$Obj | Select-Object "ComputerName", "Date", "IsOnline", "PasswordChangeStatus", "DetailedStatus" | Export-Csv -Append -Path ".\output.csv" -NoTypeInformation

    If($Status -eq "FAILED" -or $IsOnline -eq "OFFLINE") {
        $Stream.Writeline("$Computer `t $IsOnline `t $Status")
    }
}

$res.ToArray() | Format-Table ComputerName, Date, IsOnline, PasswordChangeStatus, DetailedStatus -AutoSize

#This will output 1 file, with all the computers in it, with only 1 set of headers.
$res.ToArray() | Select-Object "ComputerName", "Date", "IsOnline", "PasswordChangeStatus", "DetailedStatus" | Export-Csv -Append -Path ".\output.csv" -NoTypeInformation

它会产生这样的结果

ComputerName Date                IsOnline PasswordChangeStatus DetailedStatus
------------ ----                -------- -------------------- --------------
SERVERA      02/11/2019 11:05:57 ONLINE   SUCCESS
SERVERB      02/11/2019 11:05:57 ONLINE   SUCCESS

我猜测是因为您继续执行Format-Table cmdlet,所以控制台不知道您要输出相同的对象类型。因此,由于您多次调用它,因此必须确保将输出表显式解析到控制台。当您将事物放入数组中,然后只调用一次Format-Table时-您将获得如图所示的预期结果。

请注意,我也将Export-Csv从您的foreach中移了出来,效果也与预期的一样。