问题:
希望更改显示的错误消息,表示需要将“-passed”、“-warning”或“-failed”包含在 cmdlet 参数中,或者不关心这三个参数是否丢失并写入消息(假设它在那里) 。
解释:
创建了一个接受三个参数的函数:一条消息、第二条消息和消息状态(通过、
失败,警告)。我收到默认错误消息“无法使用指定的命名解析参数”
参数。”无论您是否通过以下方式传递消息,都会发生这种情况:
PS C:\> Write-Message;
Write-Message : Parameter set cannot be resolved using the specified named parameters.
...
//or
PS C:\> Write-Message -Message "Hello World";
但如果您输入“status”参数,它将毫无问题地工作:
PS C:\> Write-Message -Message "Hello World" -Passed;
Hello World
(“Hello World”在这里应该是绿色,但 Stack Overflow 还没有这个功能)
有问题的函数:
Function Write-Message {
param(
[string]$Message,
[string]$MessageTwo,
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName = $true, ParameterSetName ="Passed")][switch]$Passed,
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName = $true, ParameterSetName ="Warning")][switch]$Warning,
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName = $true, ParameterSetName ="Failed")][switch]$Failed
);
$NewLineNeeded = [string]::IsNullOrEmpty($MessageTwo);
if ($Passed){
$color = 'green';
}
if($Warning){
$color = 'yellow';
}
if($Failed){
$color = 'red';
}
if($Passed -or $Warning -or $Failed){
if(!$NewLineNeeded){
Write-Host $MessageOne -NoNewline;
Write-Host $MessageTwo -ForegroundColor $color;
} else {
Write-Host $Message -ForegroundColor $color;
}
}
}