Check whether a variable is null

10,350

Solution 1

Since you're trying to assign $myCredential with Get-Credential in the case of it being absent, then I assume you want your parameter to be a [PSCredential].

In that case, strongly type your parameter, and mark it as mandatory (by the way [ref] is not needed at all :

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

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

This way, you really don't have to do any checking at all. Making it Mandatory lets PowerShell enforce that for you, and making it a [PSCredential] ensures that the object is a valid [PSCredential] from the start.

The only other case you might want to check for, depending on what you're doing with the credential, is an empty credential.

To do that you can compare it to [PSCredential]::Empty, and you can do it in a validation attribute so it gets done on parameter binding:

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

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

You can do other validation in there if you want (checking for a certain username format, like if it needs to be an email address or something). If it's complex it may be better done within the function body, depends on the scenario.

But for the most part you probably don't need additional validation at all.

Solution 2

This works as intended. You are using a [ref] in your parameter. You can think of it as a pointer. And if you pass a variable to a pointer, the pointer will contain the address of the variable. The value doesn't matter.

A [ref] isn't a pointer, but the concept is It is an object of the type 'System.Management.Automation.PSReference'.

An object of the type PSReference saves the actual Value of the object you're referencing under the property 'Value' and when the function is complete it will save the value back to the original variable.

Your code would work if you use the 'Value'-Property of the 'mycredentials' variable in your if-statement:

  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)

I agree with briantist if there is no special reason you shouldn't be using a [ref].

Solution 3

Add the param block to your function and make it mandatory.

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

}

Results

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
Share:
10,350
phillip-from-oz
Author by

phillip-from-oz

Updated on June 04, 2022

Comments

  • phillip-from-oz
    phillip-from-oz almost 2 years

    I'd like to check if a variable is null:

    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)
    

    This code is based on: https://www.thomasmaurer.ch/2010/07/powershell-check-variable-for-null/, but this does not work.

    How can I fix this?

    ps. There is something in Stack Overflow for a string being null but not something more generic: Check if a string is not NULL or EMPTY

    • Maximilian Burszley
      Maximilian Burszley about 6 years
      You're using references wrong. In your function, you should be calling $mycredentials.Value.
  • briantist
    briantist about 6 years
    Great answer! The detailed information about using [ref] is really helpful.