在Powershell中创建表

问题描述 投票:3回答:3

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

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列。

arrays powershell multidimensional-array
3个回答
1
投票

试试这个:

使用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)
    {
    $Result = "" | Select Computer,Service,State,StartupMode
    $Result.Computer = $Computer
    $Result.Service = $Service.Name
    $Result.State = $Service.State
    $Result.StartupMode = $Service.StartMode
    $Array += $Result
    }
}

$Array

8
投票

您可以通过执行以下操作来自己创建具有所有这些属性的对象:

$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

0
投票

简化@ 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
© www.soinside.com 2019 - 2024. All rights reserved.