[英]Switch Parameter in Powershell
I've been looking all over, and i cant seem to find the way to make this work the way i want it to.我一直在寻找,但我似乎无法找到让这项工作按照我想要的方式进行的方法。
I'm new to PS Parameters and have something i think should be fairly simple...I want to be able to run a script and detect whether or not the switch is present.我是 PS 参数的新手,有一些我认为应该相当简单的东西......我希望能够运行脚本并检测开关是否存在。 Such as:
如:
myscript.ps1 -Deploy
-or- -要么-
myscript.ps1
Code, that i've been playing with:代码,我一直在玩:
function start-script {
param (
[parameter()]
[switch]$Deploy
)
if ($Deploy.IsPresent) {
Write-Host "True"
}
else {
Write-Host "False"
}
}
start-script
Running, this doesnt return any errors, but does not output the results of the write-host either.运行时,这不会返回任何错误,但也不会 output 写入主机的结果。 It basically does nothing.
它基本上什么都不做。 What am i doing wrong, and how would i get the correct outputs?
我做错了什么,我将如何获得正确的输出?
Thanks.谢谢。 M
米
EDIT: Adding Screenshot of what i am experiancing, since a few have said it should work or work with removing the .isPresent
编辑:添加我正在经历的截图,因为一些人说它应该可以工作或可以删除
.isPresent
Makes sense, this is because in your function call (the last line of your script) you're never giving the function any argument.有道理,这是因为在您的 function 调用(脚本的最后一行)中,您从未给 function 任何参数。 If you want to pass an argument to your ps1 script from an outside source you should add a
param(...)
block at the top of your script.如果你想从外部源向你的 ps1 脚本传递一个参数,你应该在脚本的顶部添加一个
param(...)
块。 I'm following with the code you already have but, in this case, I don't think a function is needed at all.我正在使用您已有的代码,但在这种情况下,我认为根本不需要 function。
Code could be simplified to this:代码可以简化为:
param (
[switch]$Deploy
)
if ($Deploy) {
Write-Host "True"
}
else {
Write-Host "False"
}
But if you want to use a function:但是如果你想使用 function:
param (
[switch]$Deploy
)
function Start-Script {
param (
[switch]$Deploy
)
if ($Deploy) {
Write-Host "True"
}
else {
Write-Host "False"
}
}
Start-Script @PSBoundParameters
PS /> .\script.ps1
False
PS /> .\script.ps1 -Deploy
True
D:\> powershell -File script.ps1
False
D:\> powershell -File script.ps1 -Deploy
True
[switch]$Deploy
only exist in the scope of your function this is why we add the param(...)
block at the top of the script.[switch]$Deploy
仅存在于 function 的 scope 中,这就是我们在脚本顶部添加param(...)
块的原因。$PSBoundParameters
can work with multiple functions.$PSBoundParameters
展开可以使用多个函数。 Example:例子:
param (
[switch]$Deploy,
[string]$Name
)
function Start-Script {
param (
[switch]$Deploy
)
"Deploy switch is: {0}" -f $Deploy.IsPresent
}
function SayHello {
param(
[string]$Name
)
"Hello $Name!"
}
# This is what @mclayton was referring to in his comment.
# If the Argument $Name is called:
if($PSBoundParameters.ContainsKey('Name'))
{
# Call the function
SayHello @PSBoundParameters
}
Start-Script @PSBoundParameters
PS /> .\script.ps1 -Name Santiago -Deploy
Hello Santiago!
Deploy switch is: True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.