首页 > 解决方案 > 在 PowerShell 输出表中添加自定义值

问题描述

我有一个应用程序 Web URL 列表,其中我试图通过Invoke-WebRequest命令方法监视 Web URL 的 HTTP 状态代码。

我通过以下命令获得了列表对象:

Invoke-WebRequest https://example.com/123 | Get-Member

在这里,我使用 statuscode 和 statusdescription 字段将其包含在输出中:

Invoke-WebRequest https://example.com/123 |
    Select-Object StatusCode, StatusDescription |
    ft -a

现在我希望在状态码和状态描述之前的输出中包含 URL 的自定义名称,以便输出如下所示

URL 状态码 StatusDescription
--- ---------- -----
abc 网页 200 OK       

标签: powershell

解决方案


如果您不需要将数据存储在变量中,只需打印即可

$URLsources = "http://fooo/fooURL1:800","http://fooo/fooURL2:800","http://fooo/fooURL2:800"

#table definition
    $tabName = "Output table"

    #Create Table object
    $table = New-Object system.Data.DataTable “$tabName”

    #columns definition
    $col1URL = New-Object system.Data.DataColumn URL,([string])
    $col2Status = New-Object system.Data.DataColumn Status,([string])
    $col3Desc = New-Object system.Data.DataColumn Desc,([string])

    #add columns
    $table.Columns.Add($col1URL)
    $table.Columns.Add($col2Status)
    $table.Columns.Add($col3Desc)


foreach($url in $URLsources){
  $result = Invoke-WebRequest $url 

  #preparation of the row
      $row = $table.NewRow()
      $row.URL= $url
      $row.Status= $result.StatusCode
      $row.Desc= $result.StatusDescription

  #add row to the table  
  $table.Rows.Add($row)

}

#print out the table
$table | format-table -AutoSize 

推荐阅读