1

Is there a way to select non empty/null elements into an array? For example:

Current csv: (The "___" represents empty such as '')

Col1     Col2
1       "hello"
2       "adsf"
3       "hi"
__
__

Result I want:

$array = (1,2,3)

2 Answers 2

3

Assuming you have enough memory to read the CSV file into memory in full, you can combine member-access enumeration with the array-filtering abilities of PowerShell's comparison operators (-ne in this case):

# Simulate reading a CSV file into an array of $objects.
# (instead of: $objects = Import-Csv ...)
$objects = 
@'
Col1,Col2
1,"hello"
2,"adsf"
3,"hi"
,"..."
,"..."
'@ | ConvertFrom-Csv

# .Col1 returns the "Col1" column values as an array,
# and -ne '' filters out the empty-string values.
$array = @($objects.Col1) -ne ''

Note:

  • @(), the array-subexpression operator, is used to ensure that $objects.Col1 returns an array of values, even if the CSV file happens to have just one data row.

  • With an array as the LHS, -ne acts as a filter (rather than returning $true or $false) and returns the subarray of matching elements (those who aren't the empty string). Note that the result too is then an array, even with a single-element LHS.


Otherwise, if the CSV file is too large to read into memory in full, you need to use a pipeline (this will be slower):

[array] $array =
@'
Col1,Col2
1,"hello"
2,"adsf"
3,"hi"
,"..."
,"..."
'@ | ConvertFrom-Csv | ForEach-Object { if ('' -ne $_.Col1) { $_.Col1 } }

Note:

  • Type constraint [array] ensures that the output collected from the pipeline is always treated as an array, even if only one value happens to be returned (the alternative would be to wrap the entire pipeline in @(...)).
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming Col1 is a string

Import-Csv C:\path\to\test.csv | ?{![string]::IsNullOrEmpty($_.Col1)}

1 Comment

Note that Import-Csv only ever creates [string] properties. Your solution returns whole rows (objects) not just the .Col1 values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.