Powershell的“特殊"功能开关参数 [英] Powershell "special" switch parameter
问题描述
我在下面具有Powershell功能
I have the powershell function below
Function Test
{
Param
(
[Parameter()]
[string]$Text = "default text"
)
Write-Host "Text : $($Text)"
}
我希望能够像下面这样调用此函数:
And I would like to be able to call this function like below :
测试-文本:应在主机上显示默认文本
Test -Text : should display the default text on the host
测试-文本另一个文本" :应在主机上显示提供的文本
Test -Text "another text" : should display the provided text on the host
我的问题是,powershell中不允许使用第一种语法.
My issue is that the first syntax is not allowed in powershell ..
关于如何实现此目标的任何想法? 我想要一种开关"参数,该参数可以采用布尔值以外的其他值.
Any ideas of how I can achieve this goal ? I would like a kind of 'switch' parameter that can take values other than boolean.
谢谢
推荐答案
您遇到的问题是参数绑定. PowerShell正在看到[string] $Text
并期望有一个值.您可以这样解决:
The problem you're running into is with parameter binding. PowerShell is seeing [string] $Text
and expecting a value. You can work around this like so:
function Test {
param(
[switch]
$Text,
[Parameter(
DontShow = $true,
ValueFromRemainingArguments = $true
)]
[string]
$value
)
if ($Text.IsPresent -and [string]::IsNullOrWhiteSpace($value)) {
Write-Host 'Text : <default text here>'
}
elseif ($Text.IsPresent) {
Write-Host "Text : $value"
}
}
注意:这是一个骇人听闻的解决方案,当不传递参数时,您应该使用默认值.
Note: this is a hacky solution and you should just have a default when parameters aren't passed.
这篇关于Powershell的“特殊"功能开关参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!