powershell 返回的哈希表不显示所有列

rjjhvcjd  于 2024-01-08  发布在  Shell
关注(0)|答案(1)|浏览(108)

当哈希表返回时,我无法让PowerShell脚本返回其他行。

Param(
    [array]$ArrayItem = ("Hello","to","the","World")
)
$inLine = @()
[int]$i=0
foreach ($item in $ArrayItem) {
    $tracking = $null
    $RandomNum = Get-Random -Maximum 100
    $tracking = $($ArrayItem[$i])
    Write-Host $tracking" - "$RandomNum
    $properties = @{}
        $properties = @{
         Title = "Tracking-"+$i
         Date = Get-Date -DisplayHint Time -Format "HH:mm:ss"
         $tracking = $RandomNum
    }
    #$properties.Add($tracking,$RandomNum)
    #$properties | Add-Member -MemberType PropertySet -Name $tracking -Value $get
    $inLine += New-Object -TypeName PSCustomObject -property $properties
    $i++
}
$inLine

字符串
我不知道该怎么做。这是输出。它缺少“to”、“the”和“world”。只显示第一列。

Date     Title      Hello
----     -----      -----
15:56:59 Tracking-0    70
15:56:59 Tracking-1
15:56:59 Tracking-2
15:56:59 Tracking-3


应该是这样的

Date     Title      Hello     to     the     world
----     -----      -----     --     ---     -----
15:56:59 Tracking-0    70
15:56:59 Tracking-1           23 
15:56:59 Tracking-2                   45
15:56:59 Tracking-3                             53

fnatzsnv

fnatzsnv1#

下面的代码可以得到你想要的输出,但是对于你要解决的问题,很可能有一个更简单的解决方案。

Param(
    [array] $ArrayItem = ('Hello', 'to', 'the', 'World')
)

$result = for ($i = 0; $i -lt $ArrayItem.Length; $i++) {
    $current = $ArrayItem[$i]
    $out = [ordered]@{
        Date  = Get-Date -DisplayHint Time -Format 'HH:mm:ss'
        Title = 'Tracking-' + $i
    }

    foreach ($property in $ArrayItem) {
        if ($property -eq $current) {
            $out[$property] = Get-Random -Maximum 100
            continue
        }

        $out[$property] = ''
    }

    [pscustomobject] $out
}

$result | Format-Table

字符串

相关问题