You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按$servername排序PSCustomObject输出并添加服务器分隔空行?

问题描述

尝试将每日服务器报告的输出按$servername变量排序,但始终无法成功,推测可能需要使用数组或Select-Object语句,恳请指点解决方向;同时希望能在每个新$servername的输出之间添加空行!

附上完整脚本:

Import-Module ActiveDirectory

$server = (Get-ADComputer -SearchBase "searchbase" -filter *).name

$scriptblock = {

# Set the server name
$serverName = $env:COMPUTERNAME

# Get the up/down status of the server
$pingResult = Test-Connection -ComputerName $server.Name -Count 1 -ErrorAction SilentlyContinue
$status = if ($pingResult.StatusCode -eq 1) {
    'Up'
}
else {
    'Down'
}

# Get the server build date
$buildDate = (Get-CimInstance -Class Win32_OperatingSystem).InstallDate

# Certificate name information
$certname = get-childitem -path Cert:\LocalMachine\My\ |
    Select friendlyname 

# Get the server certificate validity
[array] $certs = Get-ChildItem -Path Cert:\LocalMachine\My |
    Where-Object { -Not $_.PSIsContainer } |
    Sort-Object -Property NotBefore        

#Number of Certs on Machine
$certcount = (get-childitem -path Cert:\LocalMachine\my).count

# Check Trellix update
$TrellixDate = [datetime](Get-ItemProperty 'C:\Program Files\Common Files\McAfee\Engine\AMCoreUpdater\amupdate.dat').LastWriteTime.DateTime

# Operating system collection
$os = Get-CimInstance Win32_OperatingSystem | Select-Object Caption

# Disk information
[array] $diskInfo = Get-CimInstance -Class Win32_LogicalDisk -Filter 'DriveType = 3'

for ($i = 0; $i -lt [System.Math]::Max($cert.Count, $diskInfo.Count); $i++) {
    $disk = $diskInfo[$i]
    $freeSpace = $diskSize = $percent = $label = $null

    $cert = $certs[$i]

    if ($disk) {
        $label = $disk.DeviceID
        $freeSpace = $disk.FreeSpace / 1GB
        $diskSize = $disk.Size / 1GB
        $percent = '{0:P0}' -f ($freeSpace / $diskSize)
    }

    $validTo = $validFrom = $null
    if ($cert) {
        $validTo = $cert.NotAfter
        $validFrom = $cert.NotBefore
    }

  #SQL Version
   if (test-path 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server' -ErrorAction SilentlyContinue){
   $sql = (get-itemproperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server').InstalledInstances
    foreach ($i in $sql) 
    {
    $sqlver = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL').$i
    (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\$p\Setup").Version
    }
   }
   else {$sqlver = "n/a"}

#IIS version, if available
  if (Get-Service -Name W3SVC -ErrorAction SilentlyContinue){
  $IIS = (Get-ItemProperty -PATH 'HKLM:\SOFTWARE\Microsoft\InetStp\').VERSIONSTRING
           }
   else {$iis = "n/a"}

#Describing the Columns for Output
    [PSCustomObject]@{
        ServerName           = $serverName
        Status               = $status
        OperatingSystem      = $os
        BuildDate            = '{0:u}' -f $buildDate
        CertName             = $certname
        CertCreated          = $validFrom
        CertExpiration       = $validTo
        CertCount            = $certcount
        TrellixLastUpdate    = $TrellixDate
        SQLVersion           = $sqlver
        IISVersion           = $IIS
        DiskLabel            = $label
        Freespace            = '{0:N2} Gb' -f $freespace
        DiskSize             = '{0:N2} Gb' -f $disksize
        PercentFree          = $percent

                }
foreach ($serverName in 'PSCustomObject') { $obj | where-object {$_.Servername -eq $servername} | Sort-Object $servername }
#foreach ($serverName in 'PSCustomObject') { $obj | where-object {$_.Servername -eq $servername} | Sort-Object $servername }
}
}

#command to run the script on the servers

Invoke-Command -ComputerName $server -ScriptBlock $scriptblock -HideComputerName -ErrorAction SilentlyContinue|
Select-Object * -ExcludeProperty RunspaceId, PSComputerName, PSShowComputerName |
#Export-Csv e:\activetasks\server_checks\DailyServerReport.csv -NoTypeInformation -force
Export-Csv c:\Nec\DailyServerReport1.csv -NoTypeInformation -force
解决方案

1. 修复排序问题

原脚本中的排序逻辑无效,远程脚本块仅处理单台服务器数据,排序需在所有服务器数据返回后统一执行:

  • 删除远程脚本块末尾无效的foreach排序代码
  • 在Invoke-Command输出后添加Sort-Object ServerName实现全局排序

修改后的输出段代码:

Invoke-Command -ComputerName $server -ScriptBlock $scriptblock -HideComputerName -ErrorAction SilentlyContinue |
Select-Object * -ExcludeProperty RunspaceId, PSComputerName, PSShowComputerName |
Sort-Object ServerName |  # 新增:按服务器名称排序
Export-Csv c:\Nec\DailyServerReport1.csv -NoTypeInformation -force

2. 实现不同服务器间空行需求

CSV格式不支持空行(会破坏文件结构),若为控制台输出需求,可按服务器分组插入空行:

$reportData = Invoke-Command -ComputerName $server -ScriptBlock $scriptblock -HideComputerName -ErrorAction SilentlyContinue |
Select-Object * -ExcludeProperty RunspaceId, PSComputerName, PSShowComputerName |
Sort-Object ServerName

# 控制台输出时插入空行
$prevServer = $null
foreach ($item in $reportData) {
    if ($prevServer -and $item.ServerName -ne $prevServer) {
        Write-Host ""
    }
    $item | Format-Table -AutoSize
    $prevServer = $item.ServerName
}

# 正常导出CSV(无空行)
$reportData | Export-Csv c:\Nec\DailyServerReport1.csv -NoTypeInformation -force

3. 修正原脚本其他错误

  • Ping状态判断错误:Test-Connection成功时返回对象,失败时返回空,修正为:
    $status = if ($pingResult) { 'Up' } else { 'Down' }
    
  • SQL版本获取错误:修复未定义变量$p问题,收集所有实例版本:
    $sqlVersions = @()
    if (Test-Path 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server' -ErrorAction SilentlyContinue) {
        $sqlInstances = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server').InstalledInstances
        foreach ($instance in $sqlInstances) {
            $instancePath = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL').$instance
            $version = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\$instancePath\Setup").Version
            $sqlVersions += "$instance : $version"
        }
        $sqlver = $sqlVersions -join ', '
    } else {
        $sqlver = "n/a"
    }
    
  • CertName字段优化:将证书友好名称转为字符串,避免输出对象格式:
    $certname = (Get-ChildItem -Path Cert:\LocalMachine\My\ | Select-Object -ExpandProperty FriendlyName) -join ', '
    

内容的提问来源于stack exchange,提问作者BobSnarley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 10:18:11