期望的输出:
Server Data1 Data2
------ ----- -----
Server1 Stuff1 Thing1
Server2 Stuff2 Thing2
Server3 Stuff3 Thing3
问题:
我在自定义表格视图中有自定义标题的3-4个不同变量。问题是我使用ForEach并且我不确定如何将其放入表格视图中。现在,我能做的最好的事情是Write-Host "$server $stuff $thing"
并将每一个放在一行。我尝试了@{Expression={$_.Name};Label="Name"
的一些魔法,但没有到达任何地方。
重点是我在一天结束时有3个变量,我需要将它放入自定义表视图中。
$data = @("Server1", "Server2", "Server3")
while($true) {
cls
"`r"
ForEach ($server in $data) {
if (Test-Connection $server -count 1 -quiet) {
net use r: \\$server\s$\Folder /user:server\administrator password >$null
r:
$inputcount = (dir input -Recurse | Measure-Object).Count
$forwardcount = (dir forward -Recurse | Measure-Object).Count
$forwardcount = ($forwardcount-2)
if($fowardcount -lt 0) {
$forwardcount = 0
}
if($inputcount -gt 0 -or $forwardcount -gt 0) {
if($inputcount -gt 5000 -or $forwardcount -gt 200) {
$sleepless = "1"
}
Write-Host "$server" -ForegroundColor Red -NoNewline
Write-Host ": " -NoNewline
Write-Host "$inputcount" -ForegroundColor Red -NoNewline
Write-Host " - " -NoNewline
Write-Host "$forwardcount" -ForegroundColor Red
$inputcount = ""
c: >$null
net use r: /Delete >$null
} else {
Write-Host "$server" -NoNewline
Write-Host ": " -NoNewline
Write-Host "$inputcount" -NoNewline
Write-Host " - " -NoNewline
Write-Host "$forwardcount"
$inputcount = ""
c: >$null
net use r: /Delete >$null
}
}
}
}
答案 0 :(得分:5)
"Server1", "Server2", "Server3" | ForEach-Object {
# NB: Test-Connection "host" -Count 1 sometimes fails on an online host
if(Test-Connection $_ -Quiet -Count 2 -ErrorAction SilentlyContinue) {
$status = "online"
} else {
$status = "offline"
}
# PowerShell v3+
[PSCustomObject]@{
Server = $_
Status = $status
Count = 20
What = "ever"
}
# PowerShell v2
$item = New-Object -TypeName PSObject
$item | Add-Member -MemberType NoteProperty -Name Server -Value $_
$item | Add-Member -MemberType NoteProperty -Name Status -Value $status
$item | Add-Member -MemberType NoteProperty -Name Count -Value 20
$item | Add-Member -MemberType NoteProperty -Name What -Value "ever"
$item
}
返回:
Server Status Count What
------ ------ ----- ----
Server1 offline 20 ever
Server1 offline 20 ever
Server2 offline 20 ever
Server2 offline 20 ever
Server3 offline 20 ever
Server3 offline 20 ever
答案 1 :(得分:0)
这是我将使用的一般格式。 foreach
完全不正确,因为我不知道你是如何从一行数据到另一行数据的;不管它是什么,循环着。
请记住这是破坏性的; +=
删除前一个数组并创建一个新数组。然而,由于简单性和可读性,它在处理小数据集时往往是我的理想。
foreach ($line in $lines) {
[array]$tableVariable += New-Object PSObject -Property @{
Server = $server
Data1 = $stuff
Data3 = $thing
}
}