Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally excluding cmdlet arguments that are null or empty

I've written a script that calls the New-Service cmdlet to create a Windows service:

New-Service -Name $Name -BinaryPathName $ExecutablePath `
    -Credential $Credential -DisplayName $DisplayName `
    -Description $Description -StartupType $StartupType

I have a problem with the Description. If $Description is an empty string or $null I get an error:

Cannot validate argument on parameter 'Description'. 
The argument is null or empty. Provide an argument that is not null or empty, 
and then try the command again.

If I leave out the -Description parameter entirely the command runs without error:

New-Service -Name $Name -BinaryPathName $ExecutablePath `
    -Credential $Credential -DisplayName $DisplayName `
    -StartupType $StartupType

I can work around this problem via:

if ($Description)
{
    New-Service -Name $Name -BinaryPathName $ExecutablePath `
        -Credential $Credential -DisplayName $DisplayName `
        -Description $Description -StartupType $StartupType
}
else
{
    New-Service -Name $Name -BinaryPathName $ExecutablePath `
        -Credential $Credential -DisplayName $DisplayName `
        -StartupType $StartupType   
}

However, this seems verbose and clunky. Is there any way of telling a Powershell cmdlet to ignore an argument that is null or empty when calling the cmdlet?

Something along the lines of:

New-Service -Name $Name -BinaryPathName $ExecutablePath `
    -Credential $Credential -DisplayName $DisplayName `
    -Description [IgnoreIfNullOrEmpty]$Description -StartupType $StartupType
like image 457
Simon Tewsi Avatar asked Dec 11 '22 12:12

Simon Tewsi


1 Answers

Parameter splatting, documented in the conceptual about_Splatting help topic,[1] is the best approach in such cases:

# Create a hashtable with all parameters known to have values.
# Note that the keys are the parameter names without the "-" prefix.
$htParams = @{
  Name = $Name
  BinaryPathName = $ExecutablePath
  Credential = $Credential
  DisplayName = $DisplayName
  StartupType = $StartupType
}

# Only add a -Description argument if it is nonempty.
if ($Description) { $htParams.Description = $Description }

# Use the splatting operator, @, to pass the parameters hashtable.
New-Service @htParams

[1] chribonn also recommends this blog post for an introduction to splatting.

like image 154
mklement0 Avatar answered Apr 27 '23 00:04

mklement0