微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将for循环中的每一项添加到csv文件

如何解决将for循环中的每一项添加到csv文件

我正在尝试使用Power Shell来确定服务器是否基于KB安装了特定的补丁程序,如果没有,则将该名称附加到csv。我的输入文件具有系统名称,因此如果找不到安装的修补程序,我想导出该系统名称

这是我到目前为止所拥有的。导出到csv部分似乎无效。

forEach-Object{
    try{
        $status = wmic /node:@sys.csv qfe list full /format:table | findstr /i $kb_number

        if(!$status){
            $output_file = New-Item C:\temp\$kb_number.csv -ItemType File
            export-csv $output_file -append -Force
        }
        else{
            write-output $status
        }
    }
    catch{
        $error_message = $_.Exception.Message

        #write-output "the error message is" $error_message

        write-output "Could not find any system with this patch installed."
    }

}

解决方法

为什么您的代码可能会失败

我们看不到您在共享代码中在何处设置@sys.csv$kb_number的值。这些都可能使您失望。

但是真正的问题是Export-Csv。首先,您需要在循环的每次迭代中创建新的CSV。对于两个,您必须传递一些项目,以便将cmdlet导出为CSV。现在,您只提供这些值。

$output_file = New-Item C:\temp\$kb_number.csv -ItemType File
Export-csv -Path $output_file -append -Force

Export-Csv需要输入对象。您现在不给它一个。

您要导出什么?如果您只想要没有补丁的计算机列表,请执行此操作。

if(-not(Test-path C:\temp\$kb_number.csv)){
  #if file doesn't exist,make it
  $output_file = New-Item C:\temp\$kb_number.txt -ItemType File
}

#adds computer name if it doesn't have the patch
Add-Content -Path $output_file -Value $computer 

一般建议

如果不使用ForEach-Object循环,则可能会发现调试起来更容易。

ForEach

另一个麻烦源是您的代码正在$computers = Get-Content C:\pathTo\Your\ComputerList.txt ForEach($computer in $computers){ } 中使用较旧的dos命令,然后尝试使用PowerShell存储记录。如果您将对WMICwmic(命令的PowerShell本机版本)的Get-WmiObject的调用换成Get-CimInstance,则不需要这样做,并且可以使自己更轻松。>

为此,请更改以下行:

wmic /node:@sys.csv qfe list full /format:table  | findstr /i $kb_number

翻译成

$kb_number = "KB4576484"
Get-CimInstance Win32_QuickFixEngineering -Filter "HotfixID = '$kb_number'" -ComputerName $computer 


Source        Description      HotFixID      InstalledBy          InstalledOn              
------        -----------      --------      -----------          -----------              
              Update           KB4576484     NT AUTHORITY\SYSTEM  9/14/2020 12:00:00 AM  

您可以将其输出存储在变量中,然后在其上调用Export-Csv,这样应该可以。

如有疑问,请删除过滤器部件,然后将其工作以将所有修补程序导出到csv。然后通过重新添加过滤语句来增加复杂性。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。