英文:
Find out if variable is null or an array containing null variables in PowerShell
问题
我正在尝试确定一个变量是否为null 或 是否为包含null变量的数组。
因此,例如,一个简短的表达式,对于以下每一个都将匹配'false',但对于其他任何情况都将匹配'true':
$nullvariable = $null
$nullvariable1 = @($null)
$nullvariable2 = @($null, $null)
$nullvariable3 = @("1", $null)
上下文:我有一些Compare-Object调用,我试图避免'Cannot bind argument to parameter 'ReferenceObject' because it is null'错误。这里的第一个答案:https://stackoverflow.com/a/45634900/12872270 可以工作,但它的代码不够清晰易懂。
其他答案使用了一个'if'语句,这更易读,但在我的测试中,Compare-Object 不仅仅对 $null 失败,还对包含 null 条目的任何数组也失败 - 使用'if'的给定示例未考虑到这一点。
检测包含null变量的数组似乎是一个单独的问题,因此提出这个问题。
英文:
I am trying to find out if a variable is null or is an array containing null variables.
So for example, a short expression that will match 'false' for each of the following, but 'true' for anything else:
$nullvariable = $null
$nullvariable1 = @($null)
$nullvariable2 = @($null, $null)
$nullvariable3 = @("1", $null)
Context: I have some Compare-Object calls where I am trying to avoid 'Cannot bind argument to parameter 'ReferenceObject' because it is null' errors. The first answer here: https://stackoverflow.com/a/45634900/12872270 works but it's not very legible/comprehensible code.
The remaining answers use an 'if' statement which is more legible, but in my testing Compare-Object doesn't just fail for $null, but also any array containing null entries - the given examples using 'if' don't account for that.
Detecting an array containing null variables seems like a separate problem in its own right anyway, hence the question.
答案1
得分: 2
由于包含运算符可以针对标量和集合进行评估,因此在这种情况下,您可以使用-contains
或-in
与任何变量,结果将是$true
:
$null -in $nullvariable # True
$nullvariable1 -contains $null # True
$null -in $nullvariable2 # True
$nullvariable3 -contains $null # True
英文:
Since containment operators can evaluate against scalars as well as collections, in this case you can either use -contains
or -in
with any of your variables and the result would be $true
:
$null -in $nullvariable # True
$nullvariable1 -contains $null # True
$null -in $nullvariable2 # True
$nullvariable3 -contains $null # True
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论