使用powershell在csv单元格中写入多行值

gtlvzcf8  于 2023-10-13  发布在  Shell
关注(0)|答案(1)|浏览(115)

我有下面的命令和输出

$vmnetwork = Get-NetworkAdapter $getvm | select Name

此命令输出为

Name             
----             
Network adapter 1
Network adapter 2

我尝试了下面的代码将其写入csv,但它正在写入**“System.Object[]"**来代替上面的值

$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"

请让我知道我在这里做错了什么

qvtsj1bj

qvtsj1bj1#

问题是您正在尝试从NetworkAdapter获取名称。上面的返回一个对象数组(请记住,存在网络适配器不止一个的情况)。当格式不符合要求时,无法在csv中写入此数组。
修改您的代码,以便在单个字符串中加入适配器阵列。
下面的解决方案。

# 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"

如果你还需要什么,请告诉我。

相关问题