I have a function with parameters like this:
function foo {
Param(
[Parameter(Mandatory)]
[string]$foo,
[Parameter(Mandatory)]
[hashtable]$bar
)
}
if i call it like this everything works fine:
foo -foo "abc" -bar #{"a"="b"}
but if I only call foo and PowerShell asks me to specify values for my mandatory parameters, it won't accept my hashtable.
PS C:\Users\abc> foo
cmdlet foo at command pipeline position 1
Supply values for the following parameters:
foo: "abc"
bar: #{"a"="b"}
Cannot convert the "#{"a"="b"}" value of type "System.String" to type "System.Collections.Hashtable".
why does PowerShell not take my specified value?
I also tried to write it different ways like #{a=b}, "a"="b", #{a=b;}, #{"a"="b";} etc.
When you mark a parameter as Mandatory and don't specify a value (argument) for it on invocation, PowerShell automatically prompts you for a value.
Unfortunately, this automatic prompting mechanism for missing mandatory parameter values is broken (it has never worked, and still doesn't as of PowerShell v7):
You currently cannot interactively supply a value for any of the following types:
[hashtable],[scriptblock], [bool], [switch] (the latter two being uncommon as mandatory parameters) - their literal forms #{ ... }, { ... } and $true / $false are simply not recognized.
There's also no way to interactively specify $null.
Additionally, the automatic prompts, when they do work, are inconvenient (no tab completion, no re-prompting on invalid input), and therefore currently of little use.
These problems are being discussed in this GitHub issue.
Given the above, it's better to bypass the automatic prompts altogether and instead throw an error when no value was provided:
function foo {
Param(
# Use a default value that throws an error.
[string] $foo = $(Throw "Please pass a value for -foo."),
# Use a default value that throws an error.
[hashtable] $bar = $(Throw "Please pass a value for -bar.")
)
}
Note that [Parameter(Mandatory)] then mustn't be used, as that would still trigger an automatic prompt, despite the presence of a default value.
Read-Host (which is invoked automatically when this happens) always returns strings. If you want to take hashtable input like that, you will need to process the input. I would do something like:
if ($foo -is [system.Collections.hashtable]) {
//proceed
} else if ($foo -is [system.array]) {
Foreach ($fooItem in $foo) {
$myhash.add($key, $fooItem)
}
} else if ($foo -is [system.string]) {
$fooItem = $foo.split(,)
...
} else {
//error
}
Related
I've created a function in Powershell and want to pass the Parameter -Foo as a Boolean.
I've simplified my Use-Case for Visualization:
function Get-Foobar {
[CmdletBinding()]
param (
[bool]$Foo
)
if ($Foo) {
Write-Host "Foo!"
}
else {
Write-Host "Bar!"
}
}
The function works as expected, when I call the function Get-Foobar -Foo $true. But this is not what I want. Just Get-Foobar -Foo should suffice.
Referring to the documentation, specifying the parameter when calling the function should already return a true. But apparently this does not work.
You are looking for the Switch parameter:
Switch parameters are parameters with no parameter value.
Source.
Example:
Param(
[Parameter(Mandatory=$false)]
[Switch]
$Foo
)
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
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.
Thanks
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.
tl;dr
PowerShell does not support parameters with optional values.
A workaround is possible, but only for a single parameter.
Maximilian Burszley's helpful answer provides a workaround for a single parameter, via a catch-all parameter that collects all positionally passed arguments via the ValueFromRemainingArguments parameter property.
Fundamentally, though, what you're asking for is unsupported in PowerShell:
PowerShell has no support for parameters with optional values as of 7.2 - except for [switch] parameters, which are limited to [bool] values.
That is:
Any parameter you declare with a type other than [switch] invariably requires a value (argument).
The only other option is to indiscriminately collect any unbound positional arguments in a ValueFromRemainingArguments-tagged parameter, but you won't be able to associate these with any particular other bound parameter.
In other words:
If you happen to need just one optional-argument parameter, the ValueFromRemainingArguments can work for you (except that you should manually handle the case of mistakenly receiving multiple values), as shown in Maximilian Burszley's answer.
If you have two or more such parameters, the approach becomes impractical: you'd have to know in which order the parameters were passed (which PowerShell doesn't tell you) in order to associate the remaining positional arguments with the right parameters.
With [switch] parameters (using an imagined -Quiet switch as an example):
The default value - if you just pass -Quiet -is $true.
$false is typically indicated by simply not specifying the switch at all (that is, omitting -Quiet)
However, you may specify a value explicitly by following the switch name with :, followed by the Boolean value:
-Quiet:$true is the same as just -Quiet
-Quiet:$false is typically the same as omitting -Quiet; in rare cases, though, commands distinguish between an omitted switch and one with an explicit $false value; notably, the common -Confirm parameter allows use of -Confirm:$false - as opposed to omission of -Confirm - to override the value of the $ConfirmPreference preference variable.
While : as the separator between the parameter name and its argument (as opposed to the usual space char.) is supported with all parameters, with [switch] parameters it is a must so as to unequivocally signal that what follows is an argument for the switch parameter (which by default needs no argument) rather than an independent, positional argument.
The above tells us that PowerShell already has the syntax for general support of optional-argument parameters, so at some point in the future it could support them with any data type, as suggested in GitHub issue #12104.
I like #Maximilian Burszley's answer (and his name!) for String, I tweaked it for Ints:
function Optional-SwitchValue {
[CmdletBinding()]
param (
[Switch]
$Bump,
[Int]
$BumpAmount
)
Begin {
# nifty pattern lifted from https://stackoverflow.com/questions/58838941/powershell-special-switch-parameter
# default Bump to 1
if ($Bump.IsPresent -and -not $BumpAmount) {
$BumpAmount = 1
}
}
Process {
if($Bump) {
#use $BumpAmount in some way
}
}
}
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
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.
Thanks
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.
tl;dr
PowerShell does not support parameters with optional values.
A workaround is possible, but only for a single parameter.
Maximilian Burszley's helpful answer provides a workaround for a single parameter, via a catch-all parameter that collects all positionally passed arguments via the ValueFromRemainingArguments parameter property.
Fundamentally, though, what you're asking for is unsupported in PowerShell:
PowerShell has no support for parameters with optional values as of 7.2 - except for [switch] parameters, which are limited to [bool] values.
That is:
Any parameter you declare with a type other than [switch] invariably requires a value (argument).
The only other option is to indiscriminately collect any unbound positional arguments in a ValueFromRemainingArguments-tagged parameter, but you won't be able to associate these with any particular other bound parameter.
In other words:
If you happen to need just one optional-argument parameter, the ValueFromRemainingArguments can work for you (except that you should manually handle the case of mistakenly receiving multiple values), as shown in Maximilian Burszley's answer.
If you have two or more such parameters, the approach becomes impractical: you'd have to know in which order the parameters were passed (which PowerShell doesn't tell you) in order to associate the remaining positional arguments with the right parameters.
With [switch] parameters (using an imagined -Quiet switch as an example):
The default value - if you just pass -Quiet -is $true.
$false is typically indicated by simply not specifying the switch at all (that is, omitting -Quiet)
However, you may specify a value explicitly by following the switch name with :, followed by the Boolean value:
-Quiet:$true is the same as just -Quiet
-Quiet:$false is typically the same as omitting -Quiet; in rare cases, though, commands distinguish between an omitted switch and one with an explicit $false value; notably, the common -Confirm parameter allows use of -Confirm:$false - as opposed to omission of -Confirm - to override the value of the $ConfirmPreference preference variable.
While : as the separator between the parameter name and its argument (as opposed to the usual space char.) is supported with all parameters, with [switch] parameters it is a must so as to unequivocally signal that what follows is an argument for the switch parameter (which by default needs no argument) rather than an independent, positional argument.
The above tells us that PowerShell already has the syntax for general support of optional-argument parameters, so at some point in the future it could support them with any data type, as suggested in GitHub issue #12104.
I like #Maximilian Burszley's answer (and his name!) for String, I tweaked it for Ints:
function Optional-SwitchValue {
[CmdletBinding()]
param (
[Switch]
$Bump,
[Int]
$BumpAmount
)
Begin {
# nifty pattern lifted from https://stackoverflow.com/questions/58838941/powershell-special-switch-parameter
# default Bump to 1
if ($Bump.IsPresent -and -not $BumpAmount) {
$BumpAmount = 1
}
}
Process {
if($Bump) {
#use $BumpAmount in some way
}
}
}
What is the right way to check value of a switch?
function testSwitch
{
Param(
[switch] $swth
)
Write-Host "Value of swth is $swth"
if($swth.IsPresent){
Write-host "Switch is present"
}
if($swth){
Write-Host "Switch is present"
}
}
testSwitch -swth
I know both if statement works fine, but how?
$swth.IsPresent and $swth can be used interchangeably, because in a Boolean context (such as an if conditional) $swth (an instance of type [switch] representing a switch parameter) effectively returns the value of the .IsPresent property.[1]
In fact, $swth is probably preferable[2], not just for concision, but because the .IsPresent property is somewhat confusingly named:
.IsPresent doesn't indicate the presence of the switch per se, but whether its value is $true.
While specifying a switch by itself - -swth - implies both, the same isn't true if you explicitly set it to $false: Passing -swth:$false makes .IsPresent return $false, even though the switch is clearly present.
Passing $false explicitly isn't common, but has its uses, such as when opting out of a confirmation prompt with -Confirm:$false, and when programmatically constructing arguments.
Therefore, if you want to distinguish between the user not passing the switch and the user passing it with value $false, .IsPresent won't help you - you'll have to use $PSBoundParameters.ContainsKey('swth')
[1] On conversion to Boolean, which happens in method LanguagePrimitives.IsTrue(), PowerShell calls a [switch] instance's .ToBool() method, which in turn returns the private backing variable behind the .IsPresent property.
[2] The only caveat is that you must be aware that $swth is not a Boolean ([bool]), but of type [switch], which may matter in other contexts.
It would be more simple to just use an if/else clause:
Function Get-FruitDetails {
[CmdLetBinding()]
Param (
[String]$Fruit,
[Switch]$Yellow
)
Write-Verbose "Get fruit details of $Fruit"
$Result = [PSCustomObject]#{
Fruit = $Fruit
Yellow = $null
}
if ($Yellow) {
Write-Verbose 'Color is yellow'
$Result.Yellow = $true
}
else {
Write-Verbose 'Color is not yellow'
$Result.Yellow = $false
}
$Result
}
Get-FruitDetails -Fruit 'Banana' -Yellow -Verbose
Get-FruitDetails -Fruit 'Kiwi' -Verbose
This will output the following:
Fruit Yellow
----- ------
Banana True
Kiwi False
Some tips:
Avoid using Write-Host, it's meant for console programs. You're better of using Write-Verbose and adding the -Verbose switch if you want to see the messages
Try to use PowerShell approved verbs for function names. These can be easily found using Get-Verb. It will make it easier for others to see what your function does Get, Set, Remove, ...
Is it possible to set a default value on a mandatory parameter in a function?
It works without having it set as an mandatory ...
Ie.
Function Get-Hello {
[CmdletBinding()]
Param([Parameter(Mandatory=$true)]
[String]$Text = $Script:Text
)
BEGIN {
}
PROCESS {
Write-Host "$Script:Text"
Write-Host "$Text"
}
END {
}
}
$Text = "hello!"
Get-Hello
Reason for asking this is because i have a function that has some required parameters and the function works perfect with calling it with the required parameters but i also want to make it possible for these variables to be defined in the scripts that use this function in a "better presentable & editable" way along with the function to be able to be run with defining the required parameters.
Hence if defined in the script scope it should take that as default else it should prompty for the value.
Thanks in Advance,
If you targeting to PowerShell V3+, then you can use $PSDefaultParameterValues preferences variable:
$PSDefaultParameterValues['Get-Hello:Text']={
if(Test-Path Variable::Script:Text){
# Checking that variable exists, so we does not return $null, or produce error in strict mode.
$Script:Text
}
}