简体   繁体   English

CSV Output 不可读

[英]CSV Output Unreadable

I'm trying to export the results of this simple script to a.csv file.我正在尝试将这个简单脚本的结果导出到 a.csv 文件。 I get the results but it either returns information about data of the results or a long jumble of data I'm sure how to parse correctly.我得到了结果,但它要么返回有关结果数据的信息,要么返回一长串混乱的数据,我确定如何正确解析。

<# 
Will ping all devices in list and display results as a simple UP or DOWN, color coded Red or Green.
#>


$Names = Get-Content -Path "C:\TestFolder\GetNames.txt"

$Output = @() 

foreach ($name in $names)
{

    if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue)
        {
            $Result1 += "$name, up" 
            Write-Host "$name, up" -ForegroundColor Green
           
        }

    else
        
        {
          $Result2 += "$name, down" 
          Write-Host "$name, down" -ForegroundColor Red

        }
    }

$Output += $Result1, $Result2
$Output = $Output | Select-Object 

$Output | Export-Csv -Path 'C:\psCSVFiles\mycsv.csv' -NoTypeInformation

Results of this return: Length 49768 25081本次返回结果:长度 49768 25081

What am I doing wrong here?我在这里做错了什么? Thanks谢谢

Don't attempt to "format" the output strings manually - Export-Csv will take care of that part.不要尝试手动“格式化” output 字符串 - Export-Csv会处理该部分。

What you want to do is create objects with properties corresponding to the columns you want in your CSV:您要做的是创建具有与您想要在 CSV 中的列相对应的属性的对象

$Names = Get-Content -Path "C:\TestFolder\GetNames.txt"

$Output = foreach ($name in $names) {
  # test if computer is reachable/pingable
  $isUp = Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue -Quiet

  # construct output object with results
  [pscustomobject]@{
    ComputerName = $name
    Status = if($isUp){ 'Up' }else{ 'Down' }
  }
}

# Export to CSV
$Output |Export-Csv -Path 'C:\psCSVFiles\mycsv.csv' -NoTypeInformation

Alternatively, use Select-Object to modify the input strings directly using the pipeline:或者,使用Select-Object直接使用管道修改输入字符串:

Get-Content -Path "C:\TestFolder\GetNames.txt" |Select @{Name='ComputerName';Expression={$_}},@{Name='Status';Expression={if(Test-Connection -ComputerName $_ -Count 1 -ErrorAction SilentlyContinue -Quiet){'Up'}else{'Down'}}} |Export-Csv -Path 'C:\psCSVFiles\mycsv.csv' -NoTypeInformation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM