.net - Powershell function parameter type System.ConsoleColor - Missing ')' in function parameter list
问题描述
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:
Conditional
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
}
}
Splatting
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
}
}
推荐阅读
- ios - UITapGestureRecognizer 没有在 tvOS 上接收输入
- javascript - 将 jQuery 缓动 easeInExpo 函数重写为普通的 javascript 和 css
- javascript - 在 JQuery 中与淡出作斗争。如何让它与我的 Javascript 一起工作?
- javascript - AngularJS 中的 Keycloak 对象存储
- html - 内容与导航栏重叠 - 需要滚动“导航下方”
- .net - TreeView ItemSource 绑定到 ViewModel 不更新 xaml 控件的项目
- python - Python在同一张图中绘制系列系列与系列系列
- html - Angular cdk-virtual-scroll-viewport z-index 带来弹出窗口
- mysql - mysql-event 二进制记录器在一段时间后停止工作
- angular - 属性未更新传递给模态 componentProps