我在脚本输出以我希望的方式显示信息时遇到了麻烦。我想在一个表下查看每个生成的自定义对象的匹配属性(对象是在 foreach 循环中生成的,因此它们始终具有完全相同的属性),而不是像下面的脚本当前所做的那样为每个对象创建一个新表。此脚本创建对象的方式可以实现吗?如果可以,该怎么做?
function Get-Uptime
{
[CmdletBinding()]
Param
(
[Parameter(ValueFromPipeline=$true,
Position=0)]
[String[]]$ComputerName = $env:COMPUTERNAME
)
Begin {}
Process {
foreach ($computer in $ComputerName) {
$ComputerObject = [Ordered]@{"Computer Name" = $computer
"Start Time" = $null
"Uptime (Days)" = $null
"Status" = $null
"May Need Patched?" = $null}
$IsOnline = Test-Connection -ComputerName $Computer -Quiet
if ($IsOnline = $true) {
Try {
#Collect information about each computer
$WMIObject = Get-WMIObject -Class Win32_OperatingSystem -ComputerName $computer
#Convert LastBootUpTime to readable date/time
$ComputerObject.'Start Time' = $WMIObject.ConvertToDateTime($WMIObject.LastBootUpTime)
#Convert LocalDateTime to readable date/time
$ComputerObject.Uptime = $WMIObject.ConvertToDateTime($WMIObject.LocalDateTime)
#Collect the number of days that have elapsed between
$TimeElapsed = New-TimeSpan -Start $ConvertedBootUpTime -End $ConvertedLocalTime
$ComputerObject.'Uptime (Days)' = [Math]::Round($TimeElapsed.TotalDays,1)
$ComputerObject.'May Need Patched?' = If ($ComputerObject.'Uptime (Days)' -ge "30"){$True} Else{$False}
$ComputerObject.Status = "Online"
}
Catch {
Write-Error "Unable to gather uptime for $Computer"
$ComputerObject.Status = "Error"
}
}
else {
Write-Error "Computer $Computer is either non-existant or offline"
$ComputerObject.Status = "Offline"
}
[PSCustomObject]$ComputerObject | ft
}
}
End {}
}
答案1
问题是您在显示每个对象时都调用了 Format-Table。删除它即可。