2015-09-26 67 views
0

我一直在嘗試編寫一個腳本,該腳本從文本文件中ping出一系列計算機並將輸出導出到HTML文件。將PowerShell Foreach循環導出爲HTML

使用ForEach循環和if/else語句我已經能夠獲得一個在PowerShell中顯示的工作ping腳本,但一直未能將結果導出爲html文件。

當我運行HTML文件打開腳本,但只顯示一行「這裏是$日期平的結果」

我很新的PowerShell的所以任何類型的輸入或幫助,將不勝感激!當您使用Write-Host

$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 

回答

0

沒有被分配到$output。試試這個:

$output = "$MachineName,Ping Success!!,$Date" 
... 
$output = "$MachineName,Ping FAIL, please investigate cause ASAP!!" 

Write-Host告訴PowerShell直接寫入主機的顯示器。這繞過了輸出(標準輸出)流。雖然可以用Write-Output代替Write-Host,但幾乎沒有人使用Write-Output,因爲無論如何,每個默認流都是輸出流。因此,當像「Hello World」這樣的字符串到達​​管道的末端,並且沒有Out-File或Out-Printer時,默認情況下它會卡在Output流中,並且當流水線執行的結果被分配給變量,它會得到輸出流中的任何內容。

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 
    }