在export-csv

时间:2019-12-19 03:37:56

标签: powershell

我有Powershell脚本来下拉hotfixID,installedon,lastbootuptime和C驱动器中的可用空间。 (我在Google周围搜索并更改了一些所需的东西。)当无法访问PC时,它将

Write-Warning "$_ cannot be reached, skipping." 

我还想将发生故障的PC的计算机名称捕获到CSV中。我尝试过


| Export-Csv C:\test\computerDetails.csv -NoTypeInformation 

或追加,但似乎不起作用。有人可以帮忙吗?下面是我的整个脚本。


(Get-Content C:\test\serverlist.txt).Trim() | ForEach {

    If (Test-Connection -ComputerName $_ -Count 1 -Quiet) 
    {

        $update = Get-CimInstance Win32_QuickFixEngineering -ComputerName $_ | Sort-Object InstalledOn -Descending | Select-Object -First 1
        $os = Get-CimInstance win32_operatingsystem -ComputerName $_
        $disk = Get-WmiObject Win32_LogicalDisk -ComputerName $_ -Filter "DeviceID='C:'"

        $props = @{
            ComputerName = $_
            HotFixID = $update.HotFixID
            InstalledOn = $update.InstalledOn
            lastbootuptime = $os.LastBootUpTime
            FreeSpace_GB = $disk.FreeSpace / 1GB
        }
        New-Object PsObject -Property $props
    } 
    Else {
           Write-Warning "$_ cannot be reached, skipping." | Export-Csv C:\test\computerDetails.csv -NoTypeInformation
                }

} | Sort ComputerName |
        Select ComputerName,HotFixID,InstalledOn,lastbootuptime,FreeSpace_GB |
            Export-Csv C:\test\computerDetails.csv -NoTypeInformation

1 个答案:

答案 0 :(得分:1)

将其添加到CSV的主要问题是它是一个字符串。如果将错误的计算机与成功的计算机相同,则可以将它们放入相同的CSV。

我在那里添加了一个ArrayList作为存储变量,然后为每台计算机创建了一个临时PSObject来存储结果,在每个循环中覆盖该变量,但在将变量转储到变量中之前没有ArrayList最后导出。

$Errors = New-Object System.Collections.ArrayList
(Get-Content C:\test\serverlist.txt).Trim() | ForEach {
    $Temp = New-Object -TypeName PSObject
    If (Test-Connection -ComputerName $_ -Count 1 -Quiet) {
        $update = Get-CimInstance Win32_QuickFixEngineering -ComputerName $_ | Sort-Object InstalledOn -Descending | Select-Object -First 1
        $os = Get-CimInstance win32_operatingsystem -ComputerName $_
        $disk = Get-WmiObject Win32_LogicalDisk -ComputerName $_ -Filter "DeviceID='C:'"

        $props = [ordered]@{
            ComputerName   = $_
            HotFixID       = $update.HotFixID
            InstalledOn    = $update.InstalledOn
            lastbootuptime = $os.LastBootUpTime
            FreeSpace_GB   = $disk.FreeSpace / 1GB
            Error          = "Success"
        }
        $Temp | Add-Member -NotePropertyMembers $props -TypeName temp
    } Else {
        $props = [ordered]@{
            ComputerName   = $_
            Error          = "Cannot be reached"
        }
        $Temp | Add-Member -NotePropertyMembers $props -TypeName temp
        Write-Warning "$_ cannot be reached, skipping."
    }
    $Errors.Add($Temp) > $null
}
 $Errors | Export-Csv C:\temp\computerDetails.csv -NoTypeInformation -Append