2

Below I have a script that loops through a list of servers, remotes into them, grabs some data and writes it to 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?

2 Answers 2

1

Try to cast $myobj.Name to string and see if it will work:

[string]$myobj.Name
Sign up to request clarification or add additional context in comments.

1 Comment

For an [array] this will concatenate the elements with a space, whereas Write-Host displays them with newlines. You can emulate what you see with Write-Host better by using Out-String (which I edited into my answer).
0

The reason is that $myobj.Name is an array of names. When you display just the array, PowerShell displays each element of the array. But when you display an array of objects, each of which has a property which is an array, then each row has a column which contains several objects, and it so it just displays the type.

You'll have to decide how you want this represented in the CSV so that you can transform it appropriately. Do you want that column to contain a newline separated list of items, a semi-colon separated list, etc.?

| ServerName | Item1;Item2;Item3 |

This way is pretty easy, because you can simply convert the array into a single [string] (example with semicolon):

$result | Add-member -type Noteproperty -Name MyValue -Value ($myobj.Name -join ';')

To emulate what you see with Write-Host, use Out-String:

$result | Add-member -type Noteproperty -Name MyValue -Value ($myobj.Name | Out-String)

Alternatively, do you want to repeat each row depending on how many items in that column?

| ServerName | Item1 |
| ServerName | Item2 |
| ServerName | Item3 |

This way is a bit less striaghtforward, because you'll have to generate a new object for each Item, but it is doable.

Ultimately, how you achieve the various outcomes depends on what you'd like to do.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.