Home > OS >  Separate data into columns in powershell
Separate data into columns in powershell

Time:07-20

Im trying to take this code and have it separate data into columns in a table. I got Alive and IP to separate but stays in the same column.

Get-Content "C:\Users\user\Desktop\New folder\hnames.txt" |
  ForEach-Object {
    if(Test-Connection $_ -Count 1 -ErrorAction SilentlyContinue) {
        Write-Output "Alive ip","$_"
    } else {
        Write-Output "Dead ip - $_" 
    }
  } |  
 
  Sort-Object | Out-File -FilePath "C:\Users\user\Desktop\New folder\results.csv"

CodePudding user response:

For each "row" in your desired output table, create 1 object with the properties you want as "columns":

Get-Content "C:\Users\user\Desktop\New folder\hnames.txt" |ForEach-Object {
  if(Test-Connection $_ -Count 1 -ErrorAction SilentlyContinue){
    $status = 'Alive'
  }
  else {
    $status = 'Dead'
  }

  # output 1 object with two separate properties
  [pscustomobject]@{
    Status = $status
    Target = $_
  }
} |Export-Csv path\to\output.csv -NoTypeInformation
  • Related