csv 使用CUSTOMPSOBX对输出进行排序并按变量对输出进行排序

w80xi6nr  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(121)

我试图通过$servername变量对我的每日服务器报告的输出进行排序,但是,我无法得到要排序的输出。我认为它需要某种数组或选择对象字符串。有人能给我指出正确的方向吗?
另外,如果有一种方法可以用一个空行分隔每个新的$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

x8diyxa7

x8diyxa71#

我会说一个简单的$ArrayList | Sort-Object -Property ServerName | Format-Table,其中$ArrayList是一个[System.Collections.ArrayList](在大多数情况下比常规数组更好)变量,包含各种[PSCustomObject]应该可以做到这一点。
你甚至可能不需要行与行之间的空间。

wbrvyc0a

wbrvyc0a2#

下面是重写的代码,希望能展示如何捕获结果对象,对它们进行排序并写入Csv文件

Import-Module ActiveDirectory

# prepare the scriptblock to run on connected machines
$scriptblock = {
    # Operating system collection
    $os = (Get-CimInstance Win32_OperatingSystem).Caption

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

    # Disk information
    $diskInfo = @(Get-CimInstance -Class Win32_LogicalDisk -Filter 'DriveType = 3')

    # Certificate info
    $allCerts = @(Get-ChildItem -Path Cert:\LocalMachine\My)
    # Get the server certificate validity
    $certs = $allCerts | Where-Object { !$_.PSIsContainer } | Sort-Object -Property NotBefore        

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

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

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

        $validTo = $validFrom = $null
        if ($certs[$i]) {
            $validTo = $certs[$i].NotAfter
            $validFrom = $certs[$i].NotBefore
        }

        # SQL Version, if available
        $sqlver = if (Test-Path -Path 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server' -ErrorAction SilentlyContinue) {
            (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server').InstalledInstances | ForEach-Object {
                $p = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL' -ErrorAction SilentlyContinue).$_
                if ($p) { (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\$p\Setup").Version }
            } | Sort-Object -Descending | Select-Object -First 1
        }
        if (!$sqlver) { $sqlver = "n/a" }

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

        # Output info as PsCustomObject
        [PSCustomObject]@{
            ServerName        = $env:COMPUTERNAME
            Status            = 'Up'
            OperatingSystem   = $os
            BuildDate         = '{0:u}' -f $buildDate
            CertName          = $certs[$i].FriendlyName
            CertCreated       = $validFrom
            CertExpiration    = $validTo
            CertCount         = $allCerts.Count
            TrellixLastUpdate = $TrellixDate
            SQLVersion        = $sqlver
            IISVersion        = $iis
            DiskLabel         = $label
            Freespace         = '{0:N2} Gb' -f $freespace
            DiskSize          = '{0:N2} Gb' -f $disksize
            PercentFree       = $percent
        }
    }
}

# enter a valid DN for the searchbase here
$searchBase = 'CN=Computers,DC=Contoso,DC=com'
$servers = (Get-ADComputer -SearchBase $searchBase -Filter *).Name
$result  = foreach ($server in $servers) {
    # Get the up/down status of the server
    if (Test-Connection -ComputerName $server -Count 1 -Quiet -ErrorAction SilentlyContinue) { 
        Invoke-Command -ComputerName $server -ScriptBlock $scriptblock -HideComputerName -ErrorAction SilentlyContinue
    }
    else {
        # Output info as PsCustomObject for the disconnected server
        # create a similar object as for the connected servers with most elements empty
        "" | Select-Object @{Name = 'ServerName'; Expression = {$server}},
                           @{Name = 'Status'; Expression = {'Down'}},
                           OperatingSystem, BuildDate, CertName, CertCreated, CertExpiration, CertCount,
                           TrellixLastUpdate, SQLVersion, IISVersion, DiskLabel, Freespace, DiskSize, PercentFree
        }
    }

# Sort the resulting objects by property ServerName and write to CSV file
$result | Select-Object * -ExcludeProperty PS*, RunSpaceId |
          Sort-Object -Property ServerName |
          Export-Csv -Path 'C:\Nec\DailyServerReport1.csv' -NoTypeInformation -Force

字符串

相关问题