Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display only the columns needed PowerShell

Tags:

powershell

I have to display four columns but three of them each time, the column reference doesn't need to be displayed for a problem of space. This code allows to display cells which aren't in the column reference. When the cells match, the cell in the other columns disappears.

file:

  ComputerName  OtherComputerName   OtherComputer   AndAgain
    infra-1     infra-852            infra-2        infra-99
    infra-98    infra-85             infra-44       infra-23
    infra-5     infra-8              infra-1        infra-10
    infra-2     infra-55             infra-8        infra-70
    infra-62    infra-5              infra-852      infra-5

script:

$csv = Import-Csv .\test1.csv -Delimiter ';'

$ref = @($csv.ComputerName)
foreach ($row in $csv) {
  foreach ($col in 'OtherComputerName', 'OtherComputer', 'AndAgain') {
    if ($ref -contains $row.$col) { $row.$col = '' }
  }
}

$csv

the result on PS: I would like to not display the ComputerName column and retire the space between the cells.

OtherComputerName OtherComputer AndAgain
----------------- ------------- --------
infra-852                       infra-99
infra-85          infra-44      infra-23
infra-8                         infra-10
infra-55          infra-8       infra-70
                  infra-852             

the expected result:

OtherComputerName OtherComputer AndAgain
----------------- ------------- --------
infra-852         infra-44      infra-99
infra-85          infra-8       infra-23
infra-8           infra-852     infra-10
infra-55                        infra-70
like image 254
charlo Avatar asked Oct 13 '25 09:10

charlo


1 Answers

You can either list all columns/properties to include

$csv | Select-Object OtherComputerName,OtherComputer,AndAgain

or use -ExcludeProperty to remove named ones - but then there must be a least one -Property (position 0 doesn't have to be written out, simply use an asterisk for all)

$csv | Select-Object * -ExcludeProperty ComputerName 

Sample output here exactly matching your requirements:

OtherComputerName OtherComputer AndAgain
----------------- ------------- --------
infra-852                       infra-99
infra-85          infra-44      infra-23
infra-8                         infra-10
infra-55          infra-8       infra-70
                  infra-852

Not a table but a single shrinked col:

$csv|select Othercomputer|where Othercomputer -ne ''

Sample output:

OtherComputer
-------------
infra-44
infra-8
infra-852

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!