【问题标题】:How can I check if a string is null or empty in PowerShell?如何在 PowerShell 中检查字符串是否为空或为空?
【发布时间】:2012-11-24 04:30:41
【问题描述】:

在 PowerShell 中是否有一个类似 IsNullOrEmpty 的内置函数来检查字符串是否为空或空?

到目前为止我找不到它,如果有内置的方法,我不想为此编写函数。

【问题讨论】:

标签: .net string powershell null


【解决方案1】:

你们太难了。 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

【讨论】:

  • @pencilCake 是的,我在说什么,上面的例子显示了它的实际效果。测试不会检查的是 IsNullOrWhitespace()。
  • 比 [string]::IsNullOrEmpty(...) 干净得多
  • @VertigoRay 请参阅我上面的第一条评论,我建议在该场景中使用IsNullOrWhitespace()。但是在使用 PowerShell 编写脚本 11 年后,我发现我需要很少进行字符串测试。 :-)
  • "KeithHill。抱歉这仍然不安全,因为您的意图尚不清楚。当您使用 [string]::IsNullOrEmpty 时,您绝对清楚。IMO,Powershell 是一个最奇怪的创造 - 大多数有时它非常丰富,但仍然缺少必需品。-isNullOrEmpty 谓词就是其中之一...
  • @Lee 首先你需要了解你想要什么。不这样做是所有错误的开始。一个简单的例子 - 通过删除空值来减少数组。如果您假设一个隐式布尔值(如 Keith Hill 建议的那样),您还将过滤掉具有 0、null 或空字符串或布尔值 false 的非空值。
【解决方案2】:

你可以使用IsNullOrEmpty静态方法:

[string]::IsNullOrEmpty(...)

【讨论】:

  • 我更喜欢这种方式,因为无论您是否具备 Powerhsell 知识,它的作用显而易见——这对于非 Powershell 程序员来说是有意义的。
  • 我猜你可以这样做!$var
  • 使用 PowerShell 需要注意的一点是,传递给命令行开关或函数的空字符串不会保持为空。它们被转换为空字符串。请参阅connect.microsoft.com/PowerShell/feedback/details/861093/… 上的 Microsoft Connect 错误。
  • 考虑使用 [String]::IsNullOrWhiteSpace(...) 来验证空格。
  • @ShayLevy 小心!。这仅适用于较新版本的 PowerShell。 !-not 的别名
【解决方案3】:

除了[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] 就足够了。
  • 这些隐式转换是最危险的。您需要确保您具有确切的字符串类型。考虑 $string=@(0) - 很有可能发生......
【解决方案4】:

如果它是函数中的参数,您可以使用ValidateNotNullOrEmpty 验证它,如您在此示例中所见:

Function Test-Something
{
    Param(
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]$UserName
    )

    #stuff todo
}

【讨论】:

  • 这是迄今为止更好的方法。虽然,这并不是所提问题的完全解决方案。
【解决方案5】:

就我个人而言,我不接受将空格 ($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'}

非空

【讨论】:

  • .Net 有 String::IsNullOrEmpty 供您使用。
【解决方案6】:

[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

【讨论】:

    【解决方案7】:

    我有一个必须在计算机上运行的 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
    【解决方案8】:
    # cases
    $x = null
    $x = ''
    $x = ' '
    
    # test
    if ($x -and $x.trim()) {'not empty'} else {'empty'}
    or
    if ([string]::IsNullOrWhiteSpace($x)) {'empty'} else {'not empty'}
    

    【讨论】:

      【解决方案9】:

      以纯 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())
      

      取决于你想要做什么。

      【讨论】:

        【解决方案10】:

        请注意,"if ($str)""IsNullOrEmpty" 测试并非在所有情况下都同样有效:$str=0 的赋值对两者都产生错误,并且根据预期的程序语义,这可能会产生意外。

        【讨论】:

        • $str=0 不是一个好的编码习惯。 $str='0' 将毫无疑问地确定 IsNullOrEmpty 的预期结果。
        【解决方案11】:

        Keith Hill 答案的扩展(考虑空格):

        $str = "     "
        if ($str -and $version.Trim()) { Write-Host "Not Empty" } else { Write-Host "Empty" }
        

        这对于空值、空字符串和带有空格的字符串返回“Empty”,对于其他所有内容返回“Not Empty”。

        【讨论】:

          【解决方案12】:

          您可以使用带有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
              }
          }
          

          【讨论】:

            【解决方案13】:

            有些相关的 hack - 您可以像这样排除空值(例如 Excel 习惯在复制到 PowerShell 时包含一个额外的空单元格):

            get-clipboard | ? {$_}
            

            【讨论】:

            • 什么是get-clipboard,它与这个问题有什么关系?如果这是我认为的那样,OP 并没有表示他们正在尝试检查 Windows 剪贴板存储中第一项的值(在这种情况下,这不会回答问题)。
            猜你喜欢
            • 2015-06-05
            • 2010-10-23
            • 2017-08-19
            • 1970-01-01
            • 2015-06-12
            • 2020-05-29
            • 2017-01-10
            • 2010-09-24
            • 2011-11-25
            相关资源
            最近更新 更多