powershell - 检查变量是否为空

标签 powershell null parameter-passing

我想检查一个变量是否为空:

function send_null_param ([ref]$mycredentials){
  if (! $mycredentials) {
    Write-Host 'Got no credentials'
    $mycredentials = Get-Credential 'mydomain.com\myuserid' 
  } else {
    Write-Host 'Got credentials'
  }
}

$myidentifier = $null

send_null_param ([ref]$myidentifier)

此代码基于: https://www.thomasmaurer.ch/2010/07/powershell-check-variable-for-null/ , 但这不起作用。

我该如何解决这个问题?

附言。 Stack Overflow 中有一个字符串为 null 但不是更通用的东西: Check if a string is not NULL or EMPTY

最佳答案

因为你试图在 Get-Credential 不存在的情况下分配 $myCredential ,所以我假设你希望你的参数是 [PSCredential]

在这种情况下,强类型参数,并将其标记为强制性的(顺便说一句,根本不需要 [ref] :

function Get-MyCredential {
[CmdletBinding()]
param(
    [Parameter(Mandatory=$true)]
    [PSCredential]
    $Credential
)

    Write-Host "Got credential with username '$($Credential.Username)'"
}

这样,您实际上根本不需要进行任何检查。将其设为强制性可让 PowerShell 为您强制执行此操作,并将其设为 [PSCredential] 可确保该对象从一开始就是有效的 [PSCredential]

根据您对凭据所做的操作,您可能想要检查的唯一其他情况是空凭据。

要做到这一点,您可以将它与 [PSCredential]::Empty 进行比较,并且您可以在验证属性中进行比较,以便在参数绑定(bind)时完成:

function Get-MyCredential {
[CmdletBinding()]
param(
    [Parameter(Mandatory=$true)]
    [PSCredential]
    [ValidateScript( {
        $_ -ne [PSCredential]::Empty
    } )
    $Credential
)

    Write-Host "Got credential with username '$($Credential.Username)'"
}

如果需要,您可以在那里进行其他验证(检查特定的用户名格式,例如它是否需要是电子邮件地址或其他内容)。如果它很复杂,则最好在函数体内完成,具体取决于场景。

但在大多数情况下,您可能根本不需要额外的验证。

关于powershell - 检查变量是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48255553/

相关文章:

.net - 了解运行代码内时间计数器和代码外时间计数器之间的区别

r - 将值与 null 进行比较。为什么这是真的?

haskell - 将非空列表传递给函数

JavaScript 和 Java 通信

powershell - PS 中 "Access is denied"调用期间出现 "New-Item"错误

powershell - 为什么 Fake/F# 通配在 UNC 路径上不起作用

ios - 通过另一个 ViewController 访问 ViewController 的变量

mysql - DATE() 类型字段在 JOIN 查询中显示为 0000-00-00

ios - 传递对实例变量的引用?

string - 使用 PowerShell 4.0 从变量输入中删除空格