Powershell 检查变量是否为空
我想检查变量是否为空:Powershell 检查变量是否为空,powershell,null,parameter-passing,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 =
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)
此代码基于:
,
但这是行不通的
我怎样才能解决这个问题
另外,StackOverflow中有一些字符串为null的内容,但不是更一般的内容:
既然您试图在缺少
$myCredential
的情况下使用获取凭证
分配$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进行比较,并且可以在验证属性中执行此操作,以便在参数绑定中执行此操作:
function Get-MyCredential {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[PSCredential]
[ValidateScript( {
$_ -ne [PSCredential]::Empty
} )
$Credential
)
Write-Host "Got credential with username '$($Credential.Username)'"
}
如果需要,您可以在那里进行其他验证(检查特定的用户名格式,例如是否需要电子邮件地址或其他内容)。如果比较复杂,则最好在函数体中进行验证,具体取决于场景
但是,在大多数情况下,您可能根本不需要额外的验证。这可以按预期工作。您在参数中使用[ref]。您可以将其视为指针。如果将变量传递给指针,指针将包含变量的地址。值无关紧要
[ref]不是指针,但概念是它是“System.Management.Automation.PSReference”类型的对象
PSReference类型的对象会将您正在引用的对象的实际值保存在属性“Value”下,当函数完成时,它会将值保存回原始变量
如果在if语句中使用“mycredentials”变量的“Value”属性,则代码将正常工作:
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的观点,如果没有特殊原因,您不应该使用[ref]。将参数块添加到您的函数中,并使其成为必需的
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
您使用的引用错误。在函数中,您应该调用$mycredentials.Value
。回答得很好!有关使用[ref]
的详细信息非常有用。