I'm trying to create a cmdlet function in powershell with 2 arguments. I want one of those 2 arguments to be a ConsoleColor but ISE complains and says there is a Missing ')' in function parameter list. But I can't find this missing ).
Here is my function:
function Log {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline=$true, ValueFromRemainingArguments=$true)]
[AllowNull()]
[AllowEmptyString()]
[AllowEmptyCollection()]
[string[]]$messages,
# If I remove the following parameter, everything works fine
[System.ConsoleColor]$color = Default # ISE Complains here before `=`
)
if (($messages -eq $null) -or ($messages.Length -eq 0)) {
$messages = @("")
}
foreach ($msg in $messages) {
Write-Host $msg -ForegroundColor $color
$msg | Out-File $logFile -Append
}
}
I'm not very good in powershell so it might be something stupid that I just don't know yet.
The issue has been pointed out in the comments. You can't just assign something called Default as your parameter's default value.
Since that enum doesn't have a "default" value, I'll suggest a different approach.
Don't use a default value for the parameter, then either use a conditional (bleh) or splatting (super cool) to handle that:
function Log {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline=$true, ValueFromRemainingArguments=$true)]
[AllowNull()]
[AllowEmptyString()]
[AllowEmptyCollection()]
[string[]]$messages,
[System.ConsoleColor]$color
)
if (($messages -eq $null) -or ($messages.Length -eq 0)) {
$messages = @("")
}
foreach ($msg in $messages) {
if ($color) {
Write-Host $msg -ForegroundColor $color
} else {
Write-Host $msg
}
$msg | Out-File $logFile -Append
}
}
function Log {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline=$true, ValueFromRemainingArguments=$true)]
[AllowNull()]
[AllowEmptyString()]
[AllowEmptyCollection()]
[string[]]$messages,
[System.ConsoleColor]$color
)
$params = @{}
if ($color) {
$params.ForegroundColor = $color
}
if (($messages -eq $null) -or ($messages.Length -eq 0)) {
$messages = @("")
}
foreach ($msg in $messages) {
Write-Host $msg @params
$msg | Out-File $logFile -Append
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With