如何通过此代码生成csv文件

时间:2015-05-22 21:16:44

标签: powershell csv

我正在尝试找出一种使用WMI收集5条信息的方法,并将该信息放入数组中,然后将其导出到csv文件中。任何帮助将不胜感激。这是代码:

$Servers = get-content "c:\temp\HH_Servers.txt"
foreach ($Server in $Servers){
    $GenItems2 = gwmi Win32_OperatingSystem -Comp $Server
    $Software = gwmi Win32_Product -Comp $Server
    $systeminfo = foreach ($objItem in $GenItems2){
    $objItem.Caption
}

#Populate Software Sheet
$softwareinfo = foreach ($objItem in $Software){
    $Server
    $objItem.Name
    $objItem.Vendor
    $objItem.Version
    }
}

1 个答案:

答案 0 :(得分:1)

如果我正确地解释了代码的意图,这应该可以完成工作:

$Servers = Get-Content "c:\temp\HH_Servers.txt"

$arr = @()

foreach ($Server in $Servers){

    $GenItems2 = gwmi Win32_OperatingSystem -Comp $Server
    $Software = gwmi Win32_Product -Comp $Server

    #Populate Software Sheet
    foreach ($objItem in $Software){
        $temp = New-Object psobject
        $temp | Add-Member -MemberType NoteProperty -Name "Server" -Value $objItem.__SERVER
        $temp | Add-Member -MemberType NoteProperty -Name "Caption" -Value $GenItems2.Caption
        $temp | Add-Member -MemberType NoteProperty -Name "ServicePack" -Value $GenItems2.CsdVersion
        $temp | Add-Member -MemberType NoteProperty -Name "Name" -Value $objItem.Name
        $temp | Add-Member -MemberType NoteProperty -Name "Vendor" -Value $objItem.Vendor
        $temp | Add-Member -MemberType NoteProperty -Name "Version" -Value $objItem.Version
        $arr += $temp
    }

}

$arr | Export-Csv C:\whatever\SoftwareInfo.csv -NoTypeInformation -Encoding ASCII

我还允许自己添加一个额外的属性,其中包括操作系统的Service Pack级别(也可能是有意义的)。如果您不需要它,只需删除添加ServicePack属性的行。

如果性能很重要,你可能也会重新考虑使用wmi,因为它超级慢。如果您想了解替代方案,请参阅脚本专家讨论此事的好文章:Use PowerShell to Find Installed Software