
Question:
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
Answer1: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
Answer2:This should do your work:
$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 | Select-Object ComputerName , AndAgain