Powershell向一个CSV添加空内容而不是非空内容

问题描述

  • 我需要在一个CSV文件中包含“已安装”和“未安装”数据
  • 我认为我需要合并-OR逻辑运算符以包含TRUE / FALSE 以CSV格式输出。知道该怎么做。
  • 有一个包含许多* ServerData文件的文件夹,其中包含KB列表, 可能有重复的KB。
  • 每个服务器都有一个* ServerData文件,可能有重复的文件。
  • 我要测试其中是否包含KB2151757和KB4556403。
  • 然后将结果输出到状态为已安装或未安装的csv 已安装。
  • 当前,它仅返回安装了KB的计算机的列表。
  • 如果未找到$ patch,则当前不返回任何内容(空)。
  • 对于每台搜索到的$计算机,它需要返回指定的字段 [PSCustomObject]

我在想,也许我只需要带一个函数来查找“已安装”,一个函数来查找“未安装”,然后将结果加在一起导出即可。 Idk该怎么做。我觉得必须有一种更简单的方法。

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
        • 计算机上ExpectedPatch的输出对象为“已安装”状态
      • 其他
        • 计算机上的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
        }
    }
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...