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