如何解决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的输出对象为“未安装”状态
- 如果计算机的ServerData包含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
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。