Powershell 将空内容和非空内容添加到一个 CSV

Powershell add null content and not null content to one CSV

我在想也许我只需要一个函数来查找 'installed' 和一个函数来查找 'not installed' 并将结果加在一起导出。不知道该怎么做。我觉得一定有更简单的方法。

Click to view a sample of the CSV

$computers = Get-Item -path F:\*ServerData | Select-Object -ExpandProperty basename

$patch = gc -path F:\*ServerData | Sort-Object -Unique | Select-String KB2151757, KB4556403 #'KB(\d+)'

$output = ForEach ($computer in $computers) {

    ForEach ($kb in $patch) { 

        if ($null -eq $patch){   
            [PSCustomObject]@{
                Status = 'Not Installed' 
                Server = $computer
                KB = $kb          
            } 

      } else{  
            [PSCustomObject]@{        
                Status = 'Installed'  
                Server = $computer
                KB = $kb
            } 
        }
    }
} 
$output | Export-csv C:\KB-Report.txt -notypeinformation -delimiter ',' -encoding utf8

如果您首先按关联的计算机名称对文件进行分组,则过程变得简单(伪代码):

  • 每台电脑
    • 对于每个 ExpectedPatch
      • 如果计算机的 ServerData 包含 ExpectedPatch
        • 计算机上具有 'Installed' ExpectedPatch 状态的输出对象
      • 其他
        • 计算机上具有 'NotInstalled' ExpectedPatch 状态的输出对象

让我们试试看:

# Define the articles we're looking for
$ExpectedPatches = 'KB2151757', 'KB4556403'

# Enumerate and group data files by computer name, output as hashtable
# The resulting hashtable will have the computer name is Name and the associated files as its value
$ServerDataPerComputer = Get-Item -Path F:\*ServerData |Group BaseName -AsHashtable

foreach($Computer in $ServerDataPerComputer.GetEnumerator())
{
    foreach($Patch in $ExpectedPatches)
    {
        # Pipe all the file references to Select-String, look for the KB ID, return after the first match if any
        $Status = if($Computer.Value |Select-String "\b$Patch\b" |Select-Object -First 1){
          'Installed'
        }
        else {
          # Select-String didn't find the KB ID in any of the files
          'NotInstalled'
        }
    
        [pscustomobject]@{
          Status = $Status
          Server = $Computer.Name
          KB = $Patch
        }
    }
}