In below code, I need to check if version string is not empty then append its value to the request variable.
在下面的代码中,我需要检查版本字符串是否为空,然后将其值附加到请求变量。
if ([string]::IsNullOrEmpty($version))
{
$request += "/" + $version
}
How to check not in if condition?
如果有条件,如何检查?
4 个解决方案
#1
30
if (-not ([string]::IsNullOrEmpty($version)))
{
$request += "/" + $version
}
You can also use !
as an alternative to -not
.
你也可以用!作为-not的替代。
#2
22
You don't necessarily have to use the [string]:: prefix. This works in the same way:
您不一定要使用[string] ::前缀。这以同样的方式工作:
if ($version)
{
$request += "/" + $version
}
A variable that is null or empty string evaluates to false.
null或空字符串的变量求值为false。
#3
8
As in many other programming and scripting languages you can do so by adding !
in front of the condition
与许多其他编程和脚本语言一样,您可以添加!在条件面前
if (![string]::IsNullOrEmpty($version))
{
$request += "/" + $version
}
#4
5
If the variable is a parameter then you could use advanced function parameter binding like below to validate not null or empty:
如果变量是参数,那么您可以使用如下的高级函数参数绑定来验证非null或空:
[CmdletBinding()]
Param (
[parameter(mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$Version
)
#1
30
if (-not ([string]::IsNullOrEmpty($version)))
{
$request += "/" + $version
}
You can also use !
as an alternative to -not
.
你也可以用!作为-not的替代。
#2
22
You don't necessarily have to use the [string]:: prefix. This works in the same way:
您不一定要使用[string] ::前缀。这以同样的方式工作:
if ($version)
{
$request += "/" + $version
}
A variable that is null or empty string evaluates to false.
null或空字符串的变量求值为false。
#3
8
As in many other programming and scripting languages you can do so by adding !
in front of the condition
与许多其他编程和脚本语言一样,您可以添加!在条件面前
if (![string]::IsNullOrEmpty($version))
{
$request += "/" + $version
}
#4
5
If the variable is a parameter then you could use advanced function parameter binding like below to validate not null or empty:
如果变量是参数,那么您可以使用如下的高级函数参数绑定来验证非null或空:
[CmdletBinding()]
Param (
[parameter(mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$Version
)