【问题标题】:Adding each item from for loop to csv file将每个项目从 for 循环添加到 csv 文件
【发布时间】:2020-09-15 14:36:18
【问题描述】:

我正在尝试使用 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."
    }

}

【问题讨论】:

标签: powershell foreach


【解决方案1】:

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

我们看不到您在共享代码中设置@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){

}

另一个问题来源是您的代码在 WMIC 中使用较旧的 dos 命令,然后尝试使用 PowerShell 来存储记录。您无需执行此操作,如果将对wmic 的调用替换为Get-WmiObjectGet-CimInstance(这些命令的PowerShell 本机版本),您自己会更轻松。

为此,请更改此行:

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 即可。然后通过添加过滤语句来增加复杂性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多