将PowerShell Foreach循环导出为HTML

时间:2015-09-26 21:00:50

标签: html powershell export

我一直在尝试编写一个脚本,从文本文件中ping一组计算机并将输出导出到HTML文件。

使用ForEach循环和if / else语句我已经能够在PowerShell中显示正在运行的ping脚本,但是无法将结果导出到html文件。

当我运行脚本时,HTML文件会打开,但只会显示“这里是$ date的ping结果”行

我是PowerShell的新手,所以任何形式的输入或帮助都会受到赞赏!

$ComputersAry = Get-Content -Path "C:\Script\ping.txt"
$filepath = "C:\Script\"
$date = "{0:yyy_MM_dd-HH_mm}" -f (get-date)
$file = $filepath + "Results_" + $date + ".htm"
New-Item $filepath -type directory -force -Verbose 

$Header = @"
<style>
TABLE {border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}
TH {border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color: #6495ED;}
TD {border-width: 1px;padding: 3px;border-style: solid;border-color: black;}
</style>
<title>
LRS Ping Results
</title>
"@

Foreach ($MachineName in $ComputersAry) { 

    $PingStatus = Gwmi Win32_PingStatus -Filter "Address ='$MachineName'" | Select-Object StatusCode

        if($PingStatus.StatusCode -eq 0){
        $output = write-host "$MachineName,Ping Success!!,$Date" 
        } else {
        $output = write-host "$MachineName,Ping FAIL, please investigate cause ASAP!!" 
        } 

    }


$pre= "Here are the ping results for $date"

$output | Select-Object Name, Status, Date | ConvertTo-HTML -Head $Header -PreContent $pre | Out-File $file

Invoke-Item $file

2 个答案:

答案 0 :(得分:0)

使用$output时,Write-Host没有分配给$output = "$MachineName,Ping Success!!,$Date" ... $output = "$MachineName,Ping FAIL, please investigate cause ASAP!!" 。试试这个:

Write-Host

Write-Host告诉PowerShell直接写入主机的显示。这会绕过输出(stdout)流。虽然您可以将Write-Output替换为Write-Output,但几乎没有人使用{{1}},因为无论如何,每次转到的默认流都是输出流。所以当一个字符串像&#34; Hello World&#34;到达管道的末端,并且没有Out-File或Out-Printer,它默认会卡在输出流中,当管道执行的结果被分配给变量时,它会获得任何内容输出流。

答案 1 :(得分:0)

尝试执行以下操作,将代码保存为脚本并运行它。

PS C:\Scripts> .\Demo.ps1 | ConvertTo-Html | Out-File C:\Scripts\out.htm

$result = '' | Select Online
$ComputersAry = GC C:\Scripts\2.txt
Foreach ($MachineName in $ComputersAry) { 

 $PingStatus = Gwmi Win32_PingStatus -Filter "Address ='$MachineName'" | Select-Object StatusCode

 if($PingStatus.StatusCode -eq 0){
   $result.Online = "$MachineName,Ping Success!!" 
  } else {
   $result.Online = "$MachineName,Ping FAIL, please investigate cause ASAP!!" 
  }
   $result
  }