Makes sense, this is because in your function call (the last line of your script) you're never giving the function any argument. 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. I'm following with the code you already have but, in this case, I don't think a function is needed at all.
Code could be simplified to this:
param (
[switch] $Deploy
)
if ($Deploy) {
Write-Host "True"
return
}
Write-Host "False"
But if you want to use a function, you can leverage $PSBoundParameters as long as your function param block matches your script's one:
param (
[switch] $Deploy
)
function Start-Script {
param (
[switch] $Deploy
)
if ($Deploy) {
Write-Host "True"
return
}
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
Edit
To add a bit more context to the answer:
[switch] $Deploy only exist in the scope of your function this is why we add the param(...) block at the top of the script too, so that the function can be invoked with the same arguments as you have invoked the .ps1 script.
Splatting with $PSBoundParameters can work with multiple functions.
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 their comment.
# If the Argument $Name is called:
if ($PSBoundParameters.ContainsKey('Name')) {
# Call the function
SayHello @PSBoundParameters
}
Start-Script @PSBoundParameters
PS /> .\script.ps1 -Name world -Deploy
Hello world!
Deploy switch is: True
.\myscript.ps1 -Deploy?.\testParam.ps1 -DeployFalse.\testParam.ps1False$PSBoundParametersvariable - e.g.$PSBoundParameters.ContainsKey(“Deploy”). If you just want to know if the caller wants the switch to be enabled or not you can simply use$Deploy- Powershell will assign the default value if the user doesn’t specify it in the upstream call.-Deploy. You can also do-Deploy:$trueor-Deploy:$falseor even-Deploy:$myBoolVariableispresent. A switch parameter is to return a Boolean if specified so nothing else should be needed:if ($Deploy){.... See this answer: stackoverflow.com/a/57784149/14903754