Appending results to a CSV file.

Arosh Wijepala 161 Reputation points
2021-05-29T04:21:21.96+00:00

Hi All,

I'm using below code to generate some results and append that to an existing .csv file.

Code:

$Device = $env:computername #this is device  
$OS = (Get-WMIObject win32_operatingsystem).Caption  #this is OS  
  
$AP = @($KB)                                       
$IP = @($GetIP)   
  
Write-Host "ABNIP"                   
$AP | ForEach-Object {  
if ($IP -notcontains $_) {  
        Write-Host "$_" #this is ABNIP  
}  
   }  
  
Write-Host "NABIP"                 
$IP | ForEach-Object {  
if ($AP -notcontains $_) {  
        Write-Host "$_" #this is NABIP  
       }  
  }  

CSV:

100691-image.png

For each device, the OS would be the same but the ABNIP and NABIP would be in different size in reference with the device. Please see below.

100669-image.png

How can I append the results of the above code to this .csv file? Any help would be greatly appreciated.

Thanks in advance.

Windows for business Windows Server User experience PowerShell
{count} votes

Accepted answer
  1. Anonymous
    2021-05-31T07:39:21.06+00:00

    Hi,

    The output of Write-Host cannot be redirected. You could use the Export-Csv cmdlet to create the CSV file.

    $Device = $env:computername #this is device  
    $OS = (Get-WMIObject win32_operatingsystem).Caption  #this is OS              
    $ABNIP = $AP | ForEach-Object {  
        if ($IP -notcontains $_) { $_ }  
    }               
    $NABIP = $IP | ForEach-Object {  
        if ($AP -notcontains $_) { $_ }  
    }  
    [PSCustomObject]@{  
        "Device" = $Device  
        "OS" = $OS  
        "ABNIP" = $ABNIP -join ","  
        "NABIP" = $NABIP -join ","  
    } | Export-Csv -Path C:\temp\out.csv -NoTypeInformation  
    

    Best Regards,
    Ian Xue

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.