powershellcsv

Write multi line value in csv cell using powershell


I am having the below command and output

$vmnetwork = Get-NetworkAdapter $getvm | select Name

the output of this command is

Name             
----             
Network adapter 1
Network adapter 2

I tried the below code to write it to csv but it is writing "System.Object[]" in place of the above value

$vmnetwork = Get-NetworkAdapter $getvm | select @{Name=’Name’;Expression={[string]::join(“;”, ($_.Name))}}

        $details = [pscustomobject]@{            
                ServerName       = $servername;              
                'OS Version'     = $osversion;                 
                DataCenter       = $vmdatacenter;
                Cluster          = $Cluster;
                vCPU             = $vCPU;
                RAM              = $RAM;
                Network          = $vmnetwork
        } 

        
        $csvData = $details | Get-Member -MemberType NoteProperty | 
            ForEach-Object {
                [pscustomobject] @{Name=$_.name;Value=$details.($_.Name)}
            } | ConvertTo-Csv -NoTypeInformation

        
        $csvData | Set-Content -Path "C:\check_$servername.csv"

Please let me know what I am doing wrong here


Solution

  • The problem is that you are trying to get the Name from the NetworkAdapter. The above returns an array of objects (keep in mind that there is the case which network adapters are more than one). This array can not be written in a csv while format is not expected.

    Modify your code in order to join the arrray of adapters in a single string.

    my solution below.

    # Get the network adapter names as an array
    $vmnetwork = (Get-NetworkAdapter $getvm).Name
    
    # Join the array into a single string with a delimiter
    $networkNames = [string]::Join(';', $vmnetwork)
    
    $details = [pscustomobject]@{            
        ServerName       = $servername;              
        'OS Version'     = $osversion;                 
        DataCenter       = $vmdatacenter;
        Cluster          = $Cluster;
        vCPU             = $vCPU;
        RAM              = $RAM;
        Network          = $networkNames  # Use the joined network names here
    } 
    
    $csvData = $details | Get-Member -MemberType NoteProperty | 
        ForEach-Object {
            [pscustomobject] @{Name=$_.name;Value=$details.($_.Name)}
        } | ConvertTo-Csv -NoTypeInformation
    
    $csvData | Set-Content -Path "C:\check_$servername.csv"
    

    Please let me know if you need anything else.