【发布时间】:2012-11-24 04:30:41
【问题描述】:
在 PowerShell 中是否有一个类似 IsNullOrEmpty 的内置函数来检查字符串是否为空或空?
到目前为止我找不到它,如果有内置的方法,我不想为此编写函数。
【问题讨论】:
-
你使用的是.NET,所以你不能打电话给
String.IsNullOrEmpty吗?
标签: .net string powershell null
在 PowerShell 中是否有一个类似 IsNullOrEmpty 的内置函数来检查字符串是否为空或空?
到目前为止我找不到它,如果有内置的方法,我不想为此编写函数。
【问题讨论】:
String.IsNullOrEmpty吗?
标签: .net string powershell null
你们太难了。 PowerShell 非常优雅地处理这个问题,例如:
> $str1 = $null
> if ($str1) { 'not empty' } else { 'empty' }
empty
> $str2 = ''
> if ($str2) { 'not empty' } else { 'empty' }
empty
> $str3 = ' '
> if ($str3) { 'not empty' } else { 'empty' }
not empty
> $str4 = 'asdf'
> if ($str4) { 'not empty' } else { 'empty' }
not empty
> if ($str1 -and $str2) { 'neither empty' } else { 'one or both empty' }
one or both empty
> if ($str3 -and $str4) { 'neither empty' } else { 'one or both empty' }
neither empty
【讨论】:
IsNullOrWhitespace()。但是在使用 PowerShell 编写脚本 11 年后,我发现我需要很少进行字符串测试。 :-)
你可以使用IsNullOrEmpty静态方法:
[string]::IsNullOrEmpty(...)
【讨论】:
!。这仅适用于较新版本的 PowerShell。 ! 是 -not 的别名
除了[string]::IsNullOrEmpty 之外,为了检查 null 或空,您可以显式地将字符串转换为布尔值或在布尔表达式中:
$string = $null
[bool]$string
if (!$string) { "string is null or empty" }
$string = ''
[bool]$string
if (!$string) { "string is null or empty" }
$string = 'something'
[bool]$string
if ($string) { "string is not null or empty" }
输出:
False
string is null or empty
False
string is null or empty
True
string is not null or empty
【讨论】:
If 子句在内部将括号内的所有内容转换为单个布尔值,这意味着 if($string){Things to do for non-empty-nor-null} 或 if(!$string){Things to do for empty-or-null} 无需显式转换 [bool] 就足够了。
如果它是函数中的参数,您可以使用ValidateNotNullOrEmpty 验证它,如您在此示例中所见:
Function Test-Something
{
Param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$UserName
)
#stuff todo
}
【讨论】:
就我个人而言,我不接受将空格 ($STR3) 视为“非空”。
将只包含空格的变量传递给参数时,通常会出错,参数值可能不是'$null',而不是说它可能不是空格,一些删除命令可能会删除根文件夹如果子文件夹名称是“空格”,而不是子文件夹,这就是在许多情况下不接受包含空格的字符串的所有理由。
我发现这是实现它的最佳方式:
$STR1 = $null
IF ([string]::IsNullOrWhitespace($STR1)){'empty'} else {'not empty'}
空
$STR2 = ""
IF ([string]::IsNullOrWhitespace($STR2)){'empty'} else {'not empty'}
空
$STR3 = " "
IF ([string]::IsNullOrWhitespace($STR3)){'empty !! :-)'} else {'not Empty :-('}
空!! :-)
$STR4 = "Nico"
IF ([string]::IsNullOrWhitespace($STR4)){'empty'} else {'not empty'}
非空
【讨论】:
[string]::IsNullOrWhiteSpace() 的 PowerShell 2.0 替代品是 string -notmatch "\S"
("\S" = 任何非空白字符)
> $null -notmatch "\S"
True
> " " -notmatch "\S"
True
> " x " -notmatch "\S"
False
性能非常接近:
> Measure-Command {1..1000000 |% {[string]::IsNullOrWhiteSpace(" ")}}
TotalMilliseconds : 3641.2089
> Measure-Command {1..1000000 |% {" " -notmatch "\S"}}
TotalMilliseconds : 4040.8453
【讨论】:
我有一个必须在计算机上运行的 PowerShell 脚本,它已经过时,没有 [String]::IsNullOrWhiteSpace(),所以我自己编写了。
function IsNullOrWhitespace($str)
{
if ($str)
{
return ($str -replace " ","" -replace "`t","").Length -eq 0
}
else
{
return $TRUE
}
}
【讨论】:
.Trim() 来代替列出空格类型吗?所以应该是$str.Trim().Length -eq 0
# cases
$x = null
$x = ''
$x = ' '
# test
if ($x -and $x.trim()) {'not empty'} else {'empty'}
or
if ([string]::IsNullOrWhiteSpace($x)) {'empty'} else {'not empty'}
【讨论】:
以纯 PowerShell 方式完成此任务的另一种方法是执行以下操作:
("" -eq ("{0}" -f $val).Trim())
这会成功评估 null、空字符串和空格。我将传递的值格式化为一个空字符串来处理 null(否则调用 Trim 时 null 会导致错误)。然后只需使用空字符串评估相等性。我想我仍然更喜欢 IsNullOrWhiteSpace,但如果您正在寻找另一种方法,这将起作用。
$val = null
("" -eq ("{0}" -f $val).Trim())
>True
$val = " "
("" -eq ("{0}" -f $val).Trim())
>True
$val = ""
("" -eq ("{0}" -f $val).Trim())
>True
$val = "not null or empty or whitespace"
("" -eq ("{0}" -f $val).Trim())
>False
在无聊的时候,我玩了一些并缩短了它(尽管更神秘):
!!(("$val").Trim())
或
!(("$val").Trim())
取决于你想要做什么。
【讨论】:
请注意,"if ($str)" 和 "IsNullOrEmpty" 测试并非在所有情况下都同样有效:$str=0 的赋值对两者都产生错误,并且根据预期的程序语义,这可能会产生意外。
【讨论】:
Keith Hill 答案的扩展(考虑空格):
$str = " "
if ($str -and $version.Trim()) { Write-Host "Not Empty" } else { Write-Host "Empty" }
这对于空值、空字符串和带有空格的字符串返回“Empty”,对于其他所有内容返回“Not Empty”。
【讨论】:
您可以使用带有IsNullOrWhitespace() 和isNullOrEmpty() 静态方法的条件语句来测试空格或空值。例如,在插入MySQL 数据库之前,我会遍历我将输入的值并使用条件来避免空值或空白值。
// RowData is iterative, in this case a hashtable,
// $_.values targets the values of the hashtable
```PowerShell
$rowData | ForEach-Object {
if(-not [string]::IsNullOrEmpty($_.values) -and
-not [string]::IsNullOrWhiteSpace($_.values)) {
// Insert logic here to use non-null/whitespace values
}
}
【讨论】:
有些相关的 hack - 您可以像这样排除空值(例如 Excel 习惯在复制到 PowerShell 时包含一个额外的空单元格):
get-clipboard | ? {$_}
【讨论】:
get-clipboard,它与这个问题有什么关系?如果这是我认为的那样,OP 并没有表示他们正在尝试检查 Windows 剪贴板存储中第一项的值(在这种情况下,这不会回答问题)。