8

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
0

1 Answer 1

19

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.