检查字符串是否不为空或NULL

79
在下面的代码中,我需要检查版本字符串是否为空,然后将其值附加到请求变量中。
if ([string]::IsNullOrEmpty($version))
{
    $request += "/" + $version
}

如何在条件语句中检查 not in?


这个回答解决了你的问题吗?如何在PowerShell中检查字符串是否为空或null? - Sled
7个回答

119
if (-not ([string]::IsNullOrEmpty($version)))
{
    $request += "/" + $version
}

你也可以使用!作为-not的另一种替代方案。


70

您不一定需要使用[string] ::前缀。 这样也可以:

if ($version)
{
    $request += "/" + $version
}
一个为null或空字符串的变量会被视为false。

4
请注意这个方法,如果你的变量是0,将会返回False,请小心处理。 - Fábio Galera
2
@Fábio Galera:是的,我假设$version包含一个字符串,但这是问题的一部分。 - Palle Due
@PalleDue:是的,$version 包含一个字符串。你猜对了。谢谢! - Nilesh Khisadiya
1
0 也可以是一个字符串,结果相同。 - Fábio Galera
1
@Fábio Galera:0 怎么可能是一个字符串? - Palle Due
我的意思是,变量可以改变,但字符串仍然可以接收0。 - Fábio Galera

16

就像许多其他编程和脚本语言一样,您可以通过在条件前面添加 ! 来实现这一点。

if (![string]::IsNullOrEmpty($version))
{
    $request += "/" + $version
}

14
如果变量是参数,则可以使用如下的高级函数参数绑定来验证不为空或空字符串:
[CmdletBinding()]
Param (
    [parameter(mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [string]$Version
)

4
if (!$variablename) 
{
    Write-Host "variable is null" 
}

希望这个简单的答案能够解决问题。 来源


2

我会先将$Version定义为一个字符串。

[string]$Version

如果它是一个参数,你可以使用Samselvaprabu发布的代码。或者,如果你不想向用户显示错误,你可以做如下处理:

while (-not($version)){
    $version = Read-Host "Enter the version ya fool!"
}
$request += "/" + $version

1

如果是字符串,您可以使用[string] :: IsNullOrEmpty($version)方法。但是,我正在寻找一种通用的方法来检查Powershell中的null(不考虑数据类型)。在PowerShell中检查null(或非null)值很棘手。使用($value -eq $null)或($value -ne $null)并不总是有效。if($value)也不行。甚至使用它们可能会在以后引起问题。请阅读下面的Microsoft文章(完整阅读),以了解在PowerShell中null值的棘手之处。
我编写了以下两个函数,用于检查PowerShell中的null(或非null)值。我“相信”它们适用于任何和所有值和数据类型。希望有人会发现它们有用。我不确定为什么MS还没有将类似于此的东西本地放入PowerShell中,以使在PowerShell中处理null更容易(且更安全)。希望这可以帮助某些人。如果有人知道此方法的未见“陷阱”或问题,请在此处发布评论,以便我们知道。谢谢!
<#
*********************  
FUNCTION: ValueIsNull
*********************  
Use this function ValueIsNull below for checking for null values
rather using -eq $null or if($value) methods.  Those may not work as expected.     
See reference below for more details on $null values in PowerShell. 
[https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-null?view=powershell-7.1][1]

An if statement with a call to ValueIsNull can be written like this:
if (ValueIsNull($TheValue))    
#>

function ValueIsNull {
  param($valueToCheck)
  # In Powershell when a parameter of a function does not have a data type defined,
  # it will create the parameter as a PSObject. It will do this for 
  # an object, an array, and a base date type (int, string, DateTime, etc.)
  # However if the value passed in is $null, then it will still be $null.
  # So, using a function to check null gives us the ability to determine if the parameter
  # is null or not by checking if the parameter is a PSObject or not.
  # This function could be written more efficiently, but intentionally 
  # putting it in a more readable format.
  # Special Note: This cannot tell the difference between a parameter
  # that is a true $null and an undeclared variable passed in as the parameter.
  # ie - If you type the variable name wrong and pass that in to this function it will see it as a null.
  
  [bool]$returnValue = $True
  [bool]$isItAnObject=$True
  [string]$ObjectToString = ""
  
  try { $ObjectToString =  $valueToCheck.PSObject.ToString() } catch { $isItAnObject = $false }

  if ($isItAnObject)
  {
    $returnValue=$False
  }

  return $returnValue
}
<# 
************************
FUNCTION: ValueIsNotNull 
************************
Use this function ValueIsNotNull below for checking values for 
being "not-null"  rather than using -ne $null or if($value) methods.
Both may not work as expected.

See notes on ValueIsNull function above for more info.

ValueIsNotNull just calls the ValueIsNull function  and then reverses
the boolean result. However, having ValueIsNotNull available allows
you to avoid having  to use -eq and\or -ne against ValueIsNull results.
You can disregard this function and just use !ValueIsNull($value). 
But, it is my preference to have both for easier readability of code.

An if statement with a call to ValueIsNotNull can be written like this:
if (ValueIsNotNull($TheValue))    
#>

function ValueIsNotNull {
  param($valueToCheck)
  [bool]$returnValue = !(ValueIsNull($valueToCheck))
  return $returnValue
}

您可以使用以下 ValueIsNull 调用列表进行测试。
  $psObject = New-Object PSObject
  Add-Member -InputObject $psObject -MemberType NoteProperty -Name customproperty -Value "TestObject"
  $valIsNull = ValueIsNull($psObject)

  $props = @{
    Property1 = 'one'
    Property2 = 'two'
    Property3 = 'three'
    }
  $otherPSobject = new-object psobject -Property $props
  $valIsNull = ValueIsNull($otherPSobject)
  # Now null the object
  $otherPSobject = $null
  $valIsNull = ValueIsNull($otherPSobject)
  # Now an explicit null
  $testNullValue = $null
  $valIsNull = ValueIsNull($testNullValue)
  # Now a variable that is not defined (maybe a type error in variable name)
  # This will return a true because the function can't tell the difference
  # between a null and an undeclared variable.
  $valIsNull = ValueIsNull($valueNotDefine)

  [int32]$intValueTyped = 25
  $valIsNull = ValueIsNull($intValueTyped)
  $intValueLoose = 67
  $valIsNull = ValueIsNull($intValueLoose)
  $arrayOfIntLooseType = 4,2,6,9,1
  $valIsNull = ValueIsNull($arrayOfIntLooseType)
  [int32[]]$arrayOfIntStrongType = 1500,2230,3350,4000
  $valIsNull = ValueIsNull($arrayOfIntStrongType)
  #Now take the same int array variable and null it.
  $arrayOfIntStrongType = $null
  $valIsNull = ValueIsNull($arrayOfIntStrongType)
  $stringValueLoose = "String Loose Type"
  $valIsNull = ValueIsNull($stringValueLoose)
  [string]$stringValueStrong = "String Strong Type"
  $valIsNull = ValueIsNull($stringValueStrong)
  $dateTimeArrayLooseValue = @("1/1/2017", "2/1/2017", "3/1/2017").ForEach([datetime])
  $valIsNull = ValueIsNull($dateTimeArrayLooseValue)
  # Note that this has a $null in the array values.  Still returns false correctly.
  $stringArrayLooseWithNull = @("String1", "String2", $null, "String3")
  $valIsNull = ValueIsNull($stringArrayLooseWithNull)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接