Oct 28 2018 01:22 PM
Hello,
I am working on a function, i'm at a point where i have two variables, only one of them will have a value, the other is $null. I want to use the variable that has a value in the following code. What is the fastest or most efficient, or best way to determine this.
I know i can do an if-else condition, but i'd prefer something more classy if possible. My mind is wondering if there is such a thing as "for which ever of these two vars has a value, do this"
Oct 29 2018 04:10 AM
you can use "-ne" operator.
Examples:
PS C:\> ($null,10,$null,20 -ne $null)[0]
10
PS C:\>
PS C:\>
PS C:\> $a1=$null
PS C:\> $a2=2
PS C:\> ($a1,$a2 -ne $null)[0]
2
Explanation:
1) comma ',' operation creates array from your values/variables. Result: array with some null elements
2) '-ne' operator filter out null values. Result: array with only not-null elements
3) '[]' operator will take the 1st element from the array produced at step 2
Requirements:
Code assumes at least one variable is not null.