What's the deal with Powershell commandlet switch parameters that require a colon?
Consider Exchange 2010 management shell cmdlet Move-ActiveMailboxDatabase. The Confirm switch is a System.Management.Automation.SwitchParameter and must be used like so,
Move-ActiveMailboxDatabase -Confirm:$false
Without the colon the command fails to recognize the don't confirm switch like so,
Move-ActiveMailboxDatabase -Confirm $false
Why is that? What's the difference the colon makes there? Why Exchange2010 seems to be about the only thing I've noticed this behavior?
I've browsed through Powershell in Action and Powershell 2.0, but didn't find anything about this syntax. Scope resolution and .Net object access uses are documented on those books though.
My Google-fu found an article which claims that it explicitly forwards switch parameter values, but fails to explain what that is about.
When you do:
Move-ActiveMailboxDatabase -Confirm $false
you are not saying Confirm parameter accepts the $false. You are saying -Confirm and also passing an (separate) argument to the cmdlet with value $false.
Since Confirm is a switch, just the presence of -Confirm means it is true. Absence of -Confirm means it is false.
Let me give you a script example:
param([switch]$test)
write-host Test is $test
If you just run the script without any arguments / paramters i.e .\script.ps1 you get output:
Test is False
If you run it as .\script.ps1 -test, the output is
Test is True
If you run it as .\script.ps1 -test $false, the output is
Test is True
If you run it as .\script.ps1 -test:$false the output is
Test is False
It is in scenarios where the value for a switch variable itself has to be determined from another variable that the : is used.
For example, consider the script:
param ([boolean]$in)
function func([switch] $test){
write-host Test is $test
}
func -test:$in
Here if you run it as .\script.ps1 -in $false, you get
Test is false
If you weren't able to use the :, you would have had to write it as:
if($in){ func -test}
else { func }
The colon can be used with every parameter value but is more special in the case of switch parameters. Switch parameters don't take values, they are either present ($true) or absent ($false).
Imagine you have a function like this:
function test-switch ([string]$name,[switch]$force) { ... }
And you call it like so:
test-switch -force $false
Since switch parameters are either present or not, $false would actually bind to the Name parameter. So, how do you bind a value to a switch parameter? With the colon:
test-switch -force:$false
Now the parameter binder knows which parameter the value goes to.
Related
issue
the called powershell script will accept parameters but not all of them:
Current Set-Up and code:
I have a common folder where two .ps1 scripts are located:
DoWork.ps1
Workmanager.ps1
Workmanager.ps1 calls the Dowork.ps1:
$targetPath="M:\target"
echo "target path: $targetPath"
start powershell {.\DoWork.ps1 -target $targetPath -tempdrive D:\}
output (as expected):
target path: M:\target
DoWork.ps1 contains some start code:
param
(
[string]$tempdrive,
[string]$target,
[int] $threads = 8,
[int] $queuelength = -1
)
echo "variables:"
echo "temp drive: $tempdrive"
echo "target path: $target"
Unexpectedly, the $target is not beeing assigned. Previously I had the variable named $targetpath, which did not work either.
variables:
temp drive: D:\
target path:
Findings
It appears that the issue relies in Workmanager.ps1. Spcifying the parameter as fixed string rather than as variable will load the parameter. Any solution for this?
start powershell {.\DoWork.ps1 -target "foo" -tempdrive D:\}
When you use a ScriptBlock as an argument to powershell.exe, variables aren't going to be evaluated until after the new session starts. $targetPath has not been set in the child PowerShell process called by Workmanager.ps1 and so it has no value. This is actually an expected behavior of a ScriptBlock in general and behaves this way in other contexts too.
The solution is mentioned in the help text for powershell -?:
[-Command { - | <script-block> [-args <arg-array>] <========== THIS GUY
| <string> [<CommandParameters>] } ]
You must provide the -args parameter which will be passed to the ScriptBlock on execution (separate multiple arguments with a ,). Passed arguments are passed positionally, and must be referenced as though you were processing the arguments to a function manually using the $args array. For example:
$name = 'Bender'
& powershell { Write-Output "Hello, $($args[0])" } -args $name
However, especially with more complicated ScriptBlock bodies, having to remember which index of $args[i] contains the value you want at a given time is a pain in the butt. Luckily, we can use a little trick with defining parameters within the ScriptBlock to help:
$name = 'Bender'
& powershell { param($name) Write-Output "Hello, $name" } -args $name
This will print Hello, Bender as expected.
Some additional pointers:
The ScriptBlock can be multiline as though you were defining a function. way. The examples above are single line due to their simplicity.
A ScriptBlock is just an unnamed function, which is why defining parameters and referencing arguments within one works the same way.
To exemplify this behavior outside of powershell.exe -Command, Invoke-Command requires you to pass variables to its ScriptBlock in a similar fashion. Note however that answer uses an already-defined function body as the ScriptBlock (which is totally valid to do)
You don't need to use Start-Process here (start is its alias), at least as demonstrated in your example. You can simply use the call operator & unless you need to do something more complex than "run the program and wait for it to finish". See this answer of mine for more information.
If you opt to pass a string to powershell.exe instead, you don't need to provide arguments and your variables will get rendered in the current PowerShell process. However, so will any other unescaped variables that might be intended to set within the child process, so be careful with this approach. Personally, I prefer using ScriptBlock regardless, and just deal with the extra parameter definition and arguments.
Using the call & operator is optional when you are not executing a path rendered as a string. It can be omitted in the examples above, but is more useful like so:
& "C:\The\Program Path\Contains\spaces.exe"
& $programPathAsAVariable
I am attempting to conditionally add parameters to a command I am invoking in powershell. However, when I try, my parameter gets passed as a string. I can’t figure out how to pass it as an identifier instead.
This is my attempt so far:
$readParams = $(if ("2".Equals("2")) {"-AsSecureString"})
read-host 'Prompt' $readParams
The output I get is:
Prompt -AsSecureString:
I want to be able to set $readParams differently depending on conditions. If the condition is true get this behavior:
read-host 'Prompt' -AsSecureString
and if the condition is false get this behavior:
read-host 'Prompt'
I only want to write read-host once in my program.
How do I specify the argument dynamically without passing it as a string which causes it to become part of the prompt instead of passed as an identifier-style parameter?
The feature you're looking for is called splatting. It allows you to present a hashtable to a command and have it interpreted as parameters.
$readParams=#{}
if("2".Equals("2")) {
$readParams["AsSecureString"]=$true
}
read-host 'Prompt' #readParams
If you want to prepare multiple parameters in advance, use the splatting technique described in Mike Shepard's helpful answer, which uses a hashtable whose keys are named for the target cmdlet's parameters and also works with switch parameters (as an alternative to conditionally omitting an entry named for the switch parameter, include it unconditionally and assign $True to emulate passing the switch, and $False to emulate omitting it[1]).
To expand on Jacob Colvin's helpful answer:
For a switch parameter such as -AsSecureString (an optional Boolean parameter without argument), the challenge is that a switch's value is normally implied by its presence ($True) vs. its absence ($False)[2].
However, there is a syntax that allows passing the value explicitly, namely by appending :<expr> directly to the switch name, where <expr> is an expression whose value is converted to a Boolean; to illustrate with the automatic $True and $False variables:
-AsSecureString:$True ... same as just -AsSecureString
-AsSecureString:$False ... usually the same as not passing -AsSecureString[1]
Therefore, you can solve your problem as follows, using an expression (enclosed in (...)) directly, with no need for aux. variable $readParams:
Read-Host 'Prompt' -AsSecureString:('2' -eq '2')
* Obviously, the expression value shouldn't be invariant in real-life use.
* '2' -eq '2' is PowerShell's equivalent of "2".Equals("2"), though note that PowerShell's -eq is case-insensitive by default, so, strictly speaking, -ceq would be the closer analog.
[1] On occasion, -SomeSwitch:$False has different semantics from omitting the switch altogether, notably when overriding preference variables ad hoc. For instance, if $VerbosePreference = 'Continue' is in effect to make all cmdlets produce verbose output by default, you can use -Verbose:$False on individual commands to suppress it.
[2] Strictly speaking, a parameter variable inside a cmdlet/advanced function that represents a switch parameter is of type [switch](System.Management.Automation.SwitchParameter); however, instances of this type effectively behave like Booleans.
Somewhat confusingly, and against what the documentation says, the type's .IsPresent property reflects the effective Boolean value of the switch (on or off, loosely speaking), and not whether the switch was explicitly passed by the user.
You could set the switch to true or false depending on the condition:
$readParams = $(if ("2".Equals("2")) {$true} else {$false})
read-host 'Prompt' -AsSecureString:$readParams
I am trying to call a PS script via batch file, like so
Powershell.exe -file "C:\Scripts\Blah\Blah\Blah.ps1" -webUID "usernameValue" -webPWD "passwordValue" -Param "param value" -Param2 "param 2 value"
The issue seems to be the batch file is confusing Param and Param2. It thinks I am setting Param2 twice however Param and Param2 are separate parameters altogether. Has anyone experienced this? Is there perhaps a way to explicitly state the param names? Thanks
Param block
# Parameters
Param
(
[string]$WebUID,
[string]$WebPWD,
[string]$Param,
[string]$Param2
)
In an effort to support concise command-line use, PowerShell's "elastic syntax" allows specifying unambiguous prefix substrings of parameter names so that you only need to type as much of a parameter name as is necessary to identify it without ambiguity;
e.g., typing -p to refer to -Path is enough, if no other parameters start with p.
However, an exact match is always recognized, so that specifying -Param in your case should unambiguously match the -Param parameter, even though its full name happens to be a prefix substring of different parameter -Param2.
If the problem were an issue of ambiguity (it isn't), you'd see a different error message. For instance, were you to use the ambiguous -Para, you'd see:
Parameter cannot be processed because the parameter name 'para' is ambiguous. Possible matches include: -Param -Param2.
Instead, the wording of your error message suggests that the exact same parameter name - -Param2 - was indeed specified more than once - even though your sample code doesn't show that.
I've tested the behavior in PSv2 and PSv5.1 / 6.0 alpha 10 - it's conceivable, however, that other versions act differently due to a bug. Do let us know.
Consider an alternative approach:
If you invoked your script from within PowerShell, you could use a single, array-valued parameter - e.g. [string[]] $Params - and then simply pass as many parameters as needed, comma-separated, without needing to specify a distinct parameter name for each value.
Sadly, when invoking a script from outside of PowerShell, this approach won't work, because passing arrays isn't supported from the outside.
There is a workaround, however:
Declare the array-valued parameter decorated with [parameter(ValueFromRemainingArguments=$true)]
Invoke the script with the parameters as a space-separated list at the end of the command.
Applied to your scenario:
If your script defined its parameters as follows:
Param
(
[string]$WebUID,
[string]$WebPWD,
[parameter(ValueFromRemainingArguments=$true)]
[string[]] $Params
)
You could then invoke your script as follows:
Powershell.exe -file "C:\Scripts\Blah\Blah\Blah.ps1" `
-webUID "usernameValue" `
-webPWD "passwordValue" `
"param value" "param 2 value"
and $Params would receive an array of values: $Params[0] would receive param value, and $Params[1] would receive param 2 value.
Note that when calling from outside of PowerShell:
you must not use parameter name -Params in the invocation - just specify the values at the end.
you must not use , to separate the values - use spaces.
I'm no guru, but this looks like it's related to "Partial Parameters" and "Parameter Completion". See this article for more information.
Simply changing Param to Param1 should fix the issue.
Let's take the PowerShell statement below as an example:
powershell.exe c:\temp\windowsbroker.ps1 IIS
Is it possible to have it scripted within windowsbroker.ps1 to check for that IIS string, and if it's present to do a specific install script? The broker script would be intended to install different applications depending on what string followed it when it was called.
This may seem like an odd question, but I've been using CloudFormation to spin up application environments and I'm specifying an "ApplicationStack" parameter that will be referenced at the time when the powershell script is run so it knows which script to run to install the correct application during bootup.
What you're trying to do is called argument or parameter handling. In its simplest form PowerShell provides all arguments to a script in the automatic variable $args. That would allow you to check for an argument IIS like this:
if ($args -contains 'iis') {
# do something
}
or like this if you want the check to be case-sensitive (which I wouldn't recommend, since Windows and PowerShell usually aren't):
if ($args -ccontains 'IIS') {
# do something
}
However, since apparently you want to use the argument as a switch to trigger specific behavior of your script, there are better, more sophisticated ways of doing this. You could add a Param() section at the top of your script and check if the parameter was present in the arguments like this (for a list of things to install):
Param(
[Parameter()]
[string[]]$Install
)
$Install | ForEach-Object {
switch ($_) {
'IIS' {
# do something
}
...
}
}
or like this (for a single option):
Param(
[switch]$IIS
)
if ($IIS.IsPresent) {
# do something
}
You'd run the script like this:
powershell "c:\temp\windowsbroker.ps1" -Install "IIS",...
or like this respectively:
powershell "c:\temp\windowsbroker.ps1" -IIS
Usually I'd prefer switches over parameters with array arguments (unless you have a rather extensive list of options), because with the latter you have to worry about spelling of the array elements, whereas with switches you got a built-in spell check.
Using a Param() section will also automatically add a short usage description to your script:
PS C:\temp> Get-Help windowsbroker.ps1
windowsbroker.ps1 [-IIS]
You can further enhance this online help to your script via comment-based help.
Using parameters has a lot of other advantages on top of that (even though they probably aren't of that much use in your scenario). You can do parameter validation, make parameters mandatory, define default values, read values from the pipeline, make parameters depend on other parameters via parameter sets, and so on. See here and here for more information.
Yes, they are called positional parameters. You provide the parameters at the beginning of your script:
Param(
[string]$appToInstall
)
You could then write your script as follows:
switch ($appToInstall){
"IIS" {"Install IIS here"}
}
Here's my script (test.ps1):
[CmdLetBinding()]
Param
(
[parameter(Mandatory=$true)][string]$environment,
[switch][bool]$continue=$true
)
Write-Host $environment
Write-Host $continue
Question:
If I invoke this script by giving an argument which is a substring of the parameter I specified in the script like this: PS> .\test.ps1 -envi:blah, PowerShell doesn't seem to check the argument name. I want PowerShell to enforce parameter spelling, i.e., it should only accept -environment which matches the parameter name in the script. For anything else, it should raise an exception. Is that doable? How do I do that?
Thanks.
It's not pretty, but it will keep you from using anything except -environment as a parameter name.
Param
(
[parameter(Mandatory=$true)][string]$environment,
[parameter()]
[ValidateScript({throw "Invalid parameter. 'environment' required."})]
[string]$environmen,
[switch][bool]$continue=$true
)
Write-Host $environment
Write-Host $continue
}
Edit: As Matt noted in his comment the automatic disambiguation will force you to specify enough of the parameter name to find a unique substring match. What I'm doing here is basically giving it a parameter that satisfies all but the last character to prevent using any substring up to the last character (because it's ambiguous), and throwing an error to prevent you from using that.
And, FWIW, that could well be the ugliest parameter validation I've ever done but I don't have any better ideas right now.