YZlat
asked on
Retrieving Powershell data and outputting to csv
Below I have a script that loops through a list of servers, remotes into them, grabs some data and writes it to csv file:
The above writes 2 columns to csv file, first column is the server name - displayed correctly, but second column get the value of "System.Object[]" even though above Write-Host $myobj.Name outputs the correct value. How can i fix my code to display the correct value in a csv file?
$results = @()
$serverList = Get-Content C:\Test\Servers.txt
foreach ($server in $serverList) {
if((Test-Connection -Cn $server -BufferSize 16 -Count 1 -ea 0 -quiet))
{
$myobj = Get-ChildItem ...
Write-Host $myobj.Name
$result = New-object PSObject
$result | Add-member -type Noteproperty -Name ServerName $server.ToString()
$result | Add-member -type Noteproperty -Name MyValue -Value $myobj.Name
Write-Host $result
$results += $result
}
}
$results | export-csv -Path c:\Test\Output.csv
The above writes 2 columns to csv file, first column is the server name - displayed correctly, but second column get the value of "System.Object[]" even though above Write-Host $myobj.Name outputs the correct value. How can i fix my code to display the correct value in a csv file?
ASKER
But the thing is I want more then one result returned and then I want to add them all to an array and output the array to csv
The sample code I provided will essentially do that, joining all the elements in the array into a single string. If you want to export to a .CSV, that's your only option.
Your choice is to
either combine the Name array result into a single string, as shown by footech,
or inflate results by creating a new CSV line per Name member. This leads to say 5 rows with the same server name but different, single Name entries.
As said by footech, it is not possible to have an array in a CSV directly, you need to have a representation (enumeration with special delimiter like semi-colon, pipe, or similar).
either combine the Name array result into a single string, as shown by footech,
or inflate results by creating a new CSV line per Name member. This leads to say 5 rows with the same server name but different, single Name entries.
As said by footech, it is not possible to have an array in a CSV directly, you need to have a representation (enumeration with special delimiter like semi-colon, pipe, or similar).
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
That just joins with the "default string separator" stored in $OFS, which is a blank by default. It's the same as you see on screen, but should not use in a CSV - footech's recommendation is better. Being nit-picky " add them all to an array and output the array to csv" is not what you have done now.
ASKER
Solved myself
Open in new window
or change line 8 so the results are more limited.BTW, $server is already a string, so $server.ToString() is redundant.