检查变量是否为空

时间:2018-01-15 00:24:57

标签: 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/, 但这不起作用。

我该如何解决这个问题?

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

3 个答案:

答案 0 :(得分:4)

由于您在$myCredential缺席的情况下尝试分配Get-Credential,因此我假设您希望参数为[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进行比较,您可以在验证属性中执行此操作,以便在参数绑定上完成:

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

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

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

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

答案 1 :(得分:2)

这是按预期工作的。您在参数中使用[ref]。你可以把它想象成一个指针。如果将变量传递给指针,则指针将包含变量的地址。价值并不重要。

A [ref]不是一个指针,但概念是它是一个#System ;Management.Automation.PSReference'类型的对象。

PSReference类型的对象会保存您在“' Value'属性”下引用的对象的实际值。当函数完成时,它会将值保存回原始变量。

如果您使用' mycredentials' -Property' mycredentials'您的代码将会有效。你的if语句中的变量:

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

$myidentifier=$null

send_null_param ([ref]$myidentifier)

如果没有特殊原因你不应该使用[参考],我同意briantist。

答案 2 :(得分:1)

将param块添加到您的函数中并强制它。

Function New-Creds
{
    [CmdletBinding()]
    [Alias('nc')]

    Param
    (
        [Parameter(Mandatory=$true, 
        HelpMessage = 'This is a required field. It cannot be blank')]$MyCredentials
    )

    # Code begins here
    $MyCredentials

}

结果

New-Creds -MyCredentials 

New-Creds : Missing an argument for parameter 'MyCredentials'. Specify a parameter of type 'System.Object' and try again.
At line:1 char:11
+ New-Creds -MyCredentials
+           ~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [New-Creds], ParameterBindingException
    + FullyQualifiedErrorId : MissingArgument,New-Creds


New-Creds

cmdlet New-Creds at command pipeline position 1
Supply values for the following parameters:
(Type !? for Help.)

MyCredentials: !?

This is a required field. It cannot be blank

MyCredentials: SomeCreds
SomeCreds

New-Creds -MyCredentials AnotherCred
AnotherCred
相关问题