在Powershell中创建表



伙计们,我有一个脚本,查询服务在远程计算机。它运行两个嵌套的foreach循环,一个用于计算机列表,一个用于服务列表。我想在二维数组中捕获该过程的输出。

The desired output should be like this:
Computer    Service   State   StartupMode
-------------------------------------------
data         data      data     data
data         data      data     data
data         data      data     data
data         data      data     data

我已经获得了数据并将其呈现在控制台上,但未能将其存储在多列数组中。哈希表只能接受2列。

您可以自己创建具有所有这些属性的对象,方法如下:

$yourData = @(
    @{Computer="Data";Service="Data";State="Data";StartupMode="Data"},
    @{Computer="Data";Service="Data";State="Data";StartupMode="Data"},
    @{Computer="Data";Service="Data";State="Data";StartupMode="Data"},
    @{Computer="Data";Service="Data";State="Data";StartupMode="Data"}) | % { New-Object object | Add-Member -NotePropertyMembers $_ -PassThru }
$yourData

试试这个:

使用WMI因为Get-Service缺少StartupMode

$Array = @()
$Computers = "Computer1","Computer2","Computer3"
Foreach ($Computer in $Computers)
{
$Services = Get-WmiObject Win32_Service -ComputerName $Computer | Select name,state,startmode
    Foreach ($Service in $Services)
    {
    $Row = "" | Select Computer,Service,State,StartupMode
    $Row.Computer = $Computer
    $Row.Service = $Service.Name
    $Row.State = $Service.State
    $Row.StartupMode = $Service.StartMode
    $Array += $Row
    }
}
$Array

在@Dan的回答上略有变化,根据这篇微软博客文章使用[pscustomobject]

$yourData = @(
    [pscustomobject]@{Computer="Data";Service="Data";State="Data";StartupMode="Data"},
    [pscustomobject]@{Computer="Data";Service="Data";State="Data";StartupMode="Data"},
    [pscustomobject]@{Computer="Data";Service="Data";State="Data";StartupMode="Data"},
    [pscustomobject]@{Computer="Data";Service="Data";State="Data";StartupMode="Data"}) 
$yourData

我正在添加到@Dan和@mherzog提供的答案中,以防有人想要一个如何动态地向该表添加行的示例。

$myTable = @()
foreach($computer in $computerList) {
    $col1 = $computer
    $col2 = $(Test-Connection -ComputerName $computer -Quiet)
    $col3 = $(Get-WUList -ComputerName $computer).Count
    $myTable += [pscustomobject]@{Computer=$col1;Online=$col2;Updates=$updateCount}
}
$myTable

简化@Avshalom的回答,您可以直接将$Service添加到$Array中:

$Array = @()
$Computers = "Computer1","Computer2","Computer3"
Foreach ($Computer in $Computers)
{
$Services = Get-WmiObject Win32_Service -ComputerName $Computer | Select name,state,startmode
    Foreach ($Service in $Services)
    {
        $Array += $Service
    }
}
$Array | Format-Table

相关内容

  • 没有找到相关文章

最新更新