0

The following code

"a,b,c
1,1,1
2,,2
3,3,3" > test.csv

import-csv test.csv | select b | % { 
    Write-Host "$_ $([string]::IsNullOrEmpty($_))" 
} 

returns

@{b=1} False
@{b=} False
@{b=3} False

However, I expected the second line return True. I tried $_ -eq $null -or $_ -eq '' and none if them work?

3 Answers 3

2

The issue is that inside of the % { } block $_ does not contain the value of column b but rather an object with a b property. When you run [string]::IsNullOrEmpty($_) you are testing if this object is null or an empty string, neither of which is true.

To illustrate what's happening, compare the results of...

Import-Csv .\test.csv | Get-Member

...with the results of...

Import-Csv .\test.csv | select b | Get-Member

...with the results of...

Import-Csv .\test.csv | select -ExpandProperty b | Get-Member

One solution is to test if the b property of the object produced by select (rather than the object itself) is null or empty:

import-csv test.csv | select b | % { 
    Write-Host "$_ $([string]::IsNullOrEmpty($_.b))" 
}

Another solution is to pass only the value of column b to the % { } block:

import-csv test.csv | select -ExpandProperty b | % { 
    Write-Host "$_ $([string]::IsNullOrEmpty($_))" 
}
Sign up to request clarification or add additional context in comments.

2 Comments

AHhhh took my answer out from underneath me.
@Matt My name is Matt, too. We were predisposed to answer this way.
0

I found the following code works.

import-csv test.csv | select b | % { 
    Write-Host "$_ $($_.b -eq '')" 
} 

Is there any other solution?

Comments

0

In your example in the question there is still an object present with an empty b parameter. Consider the following which shows why you got the result you did.

PS C:\Users\matt> @{} -eq $null
False

The rest of this would be to expand the property much like in Bacon's answer

Comments

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.