我有一个脚本
foo.ps1
和一个批处理文件foo.cmd
用于双击文件Explorer中的CMD文件来启动脚本。
脚本接受开关参数,但我不知道如何提供此类参数。简单的参数还可以。
foo.ps1:
param(
[Parameter()]
[Switch]$MySwitch,
[Parameter()]
[string]$Name
)
Write-Host "`$MySwitch : $MySwitch, `$Name : $name"
foo.cmd:
Powershell -noprofile -NonInteractive -file "%~dp0\foo.ps1" -Name "abc"
如果我只用“名称”调用脚本,那就起作用。但是,如果我指定myswitch,它就停止工作:
foo2.cmd:
Powershell -noprofile -NonInteractive -File "%~dp0\foo.ps1" -Name "abc" -MySwitch:$false
错误是:
C:\temp\foo.ps1 : Impossible de traiter la transformation d'argument sur le paramètre «MySwitch». Impossible de convertir la valeur «System.String» en type « System.Management.Automation.SwitchParameter». Les paramètres booléens acceptent seulement des valeurs booléennes et des nombres, tels que $True, $False, 1 ou 0.
+ CategoryInfo : InvalidData : (:) [foo.ps1], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,foo.ps1
,当powershell.exe
's
-File
参数用于使用-此后已在
pwsh.exe
[1].。使用josefz推荐: 使用
-Command
(-c
)
-File
$false
powershell将参数视为powershell sourcecode而不是字面的参数
,在这种情况下,可以正确地识别powershell powershell powershell powershell是正确识别的。
powershell -c "& \"%~dp0\foo.ps1\" -Name 'abc' -MySwitch:$false"
注:
&
,calloperator
必须用于调用脚本文件,因为其路径已
"
炭。在要逃脱的命令行上(不是
\"
或`"
,它的工作方式insidepowershell)。
""
string
,请使用
-Command
(sic)。当您可以将脚本路径封闭在
"
中,以避免逃脱的需求,如果扩展的目录文件路径(\"...\"
)恰好包含`\"
chars,则这样的调用将会中断。本身
对于何时使用
'...'
vs.
%dp0
和适用的不同语法规则的一般指导,请参见this this Answer.。
:
您的代码已经使用了屈服的方法来传递powershell中的布尔参数:
'
(有时称为
flags)。 开关参数Imply
-File
),则暗示-Command
;如果完全毫无疑问,则暗示
[switch]
-MySwitch
typed参数。 thisPost与参数形成对比。
(powershell在内部)您(始终)您(始终)通过cancan nive nive值
$true
,请注意取消分隔仪,一个space不起作用) - 在以下方案中,这样做是仅此::
::
在情况下,您想传递一个布尔值via a via a的变量,其值是按照图表的方式。 However, some of PowerShell's
in effect default to [bool]
via their preference variable counterparts.
值得注意的示例是公共
[bool]
开关参数:相应的
[switch]
偏爱变量的值可以使通过-MySwitch:$false
以选择退出确认提示符,即使有:
的默认值($true
[1] PowerShell(core)7在使用$true
时支持以下布尔值:
Write-Host
,-NoNewLine