Accepting an optional parameter only as named, not positional - powershell

I'm writing a PowerShell script that's a wrapper to an .exe. I want to have some optional script params, and pass the rest directly to the exe. Here's a test script:
param (
[Parameter(Mandatory=$False)] [string] $a = "DefaultA"
,[parameter(ValueFromRemainingArguments=$true)][string[]]$ExeParams # must be string[] - otherwise .exe invocation will quote
)
Write-Output ("a=" + ($a) + " ExeParams:") $ExeParams
If I run with the a named param, everything is great:
C:\ > powershell /command \temp\a.ps1 -a A This-should-go-to-exeparams This-also
a=A ExeParams:
This-should-go-to-exeparams
This-also
However, if I try to omit my param, the first unnamed param is assigned to it:
C:\ > powershell /command \temp\a.ps1 This-should-go-to-exeparams This-also
a=This-should-go-to-exeparams ExeParams:
This-also
I would expect:
a=DefaultA ExeParams:
This-should-go-to-exeparams
This-also
I tried adding Position=0 to the param, but that produces the same result.
Is there a way to achieve this?
Maybe a different parameter scheme?

By default, all function parameters are positional. Windows PowerShell assigns position numbers to parameters in the order in which the parameters are declared in the function. To disable this feature, set the value of the PositionalBinding argument of the CmdletBinding attribute to $False.
have a look at How to disable positional parameter binding in PowerShell
function Test-PositionalBinding
{
[CmdletBinding(PositionalBinding=$false)]
param(
$param1,$param2
)
Write-Host param1 is: $param1
Write-Host param2 is: $param2
}

The main answer still works in version 5 (according to comments, it may have been broken for a while in version 2).
There is another option: add Position to the ValueFromRemainingArgs parameter.
Sample CommandWrapper.ps1:
param(
$namedOptional = "default",
[Parameter(ValueFromRemainingArguments = $true, Position=1)]
$cmdArgs
)
write-host "namedOptional: $namedOptional"
& cmd /c echo cmdArgs: #cmdArgs
Sample output:
>commandwrapper hello world
namedOptional: default
cmdArgs: hello world
This appears to follow from PowerShell assigning parameter positions from the first parameter with a Position designated.

Related

I want to download a software with powershell and the download script work but in function it does'not work [duplicate]

If I have a function which accepts more than one string parameter, the first parameter seems to get all the data assigned to it, and remaining parameters are passed in as empty.
A quick test script:
Function Test([string]$arg1, [string]$arg2)
{
Write-Host "`$arg1 value: $arg1"
Write-Host "`$arg2 value: $arg2"
}
Test("ABC", "DEF")
The output generated is
$arg1 value: ABC DEF
$arg2 value:
The correct output should be:
$arg1 value: ABC
$arg2 value: DEF
This seems to be consistent between v1 and v2 on multiple machines, so obviously, I'm doing something wrong. Can anyone point out exactly what?
Parameters in calls to functions in PowerShell (all versions) are space-separated, not comma separated. Also, the parentheses are entirely unneccessary and will cause a parse error in PowerShell 2.0 (or later) if Set-StrictMode -Version 2 or higher is active. Parenthesised arguments are used in .NET methods only.
function foo($a, $b, $c) {
"a: $a; b: $b; c: $c"
}
ps> foo 1 2 3
a: 1; b: 2; c: 3
The correct answer has already been provided, but this issue seems prevalent enough to warrant some additional details for those wanting to understand the subtleties.
I would have added this just as a comment, but I wanted to include an illustration--I tore this off my quick reference chart on PowerShell functions. This assumes function f's signature is f($a, $b, $c):
Thus, one can call a function with space-separated positional parameters or order-independent named parameters. The other pitfalls reveal that you need to be cognizant of commas, parentheses, and white space.
For further reading, see my article Down the Rabbit Hole: A Study in PowerShell Pipelines, Functions, and Parameters. The article contains a link to the quick reference/wall chart as well.
There are some good answers here, but I wanted to point out a couple of other things. Function parameters are actually a place where PowerShell shines. For example, you can have either named or positional parameters in advanced functions like so:
function Get-Something
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $Name,
[Parameter(Mandatory=$true, Position=1)]
[int] $Id
)
}
Then you could either call it by specifying the parameter name, or you could just use positional parameters, since you explicitly defined them. So either of these would work:
Get-Something -Id 34 -Name "Blah"
Get-Something "Blah" 34
The first example works even though Name is provided second, because we explicitly used the parameter name. The second example works based on position though, so Name would need to be first. When possible, I always try to define positions so both options are available.
PowerShell also has the ability to define parameter sets. It uses this in place of method overloading, and again is quite useful:
function Get-Something
{
[CmdletBinding(DefaultParameterSetName='Name')]
Param
(
[Parameter(Mandatory=$true, Position=0, ParameterSetName='Name')]
[string] $Name,
[Parameter(Mandatory=$true, Position=0, ParameterSetName='Id')]
[int] $Id
)
}
Now the function will either take a name, or an id, but not both. You can use them positionally, or by name. Since they are a different type, PowerShell will figure it out. So all of these would work:
Get-Something "some name"
Get-Something 23
Get-Something -Name "some name"
Get-Something -Id 23
You can also assign additional parameters to the various parameter sets. (That was a pretty basic example obviously.) Inside of the function, you can determine which parameter set was used with the $PsCmdlet.ParameterSetName property. For example:
if($PsCmdlet.ParameterSetName -eq "Name")
{
Write-Host "Doing something with name here"
}
Then, on a related side note, there is also parameter validation in PowerShell. This is one of my favorite PowerShell features, and it makes the code inside your functions very clean. There are numerous validations you can use. A couple of examples are:
function Get-Something
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[ValidatePattern('^Some.*')]
[string] $Name,
[Parameter(Mandatory=$true, Position=1)]
[ValidateRange(10,100)]
[int] $Id
)
}
In the first example, ValidatePattern accepts a regular expression that assures the supplied parameter matches what you're expecting. If it doesn't, an intuitive exception is thrown, telling you exactly what is wrong. So in that example, 'Something' would work fine, but 'Summer' wouldn't pass validation.
ValidateRange ensures that the parameter value is in between the range you expect for an integer. So 10 or 99 would work, but 101 would throw an exception.
Another useful one is ValidateSet, which allows you to explicitly define an array of acceptable values. If something else is entered, an exception will be thrown. There are others as well, but probably the most useful one is ValidateScript. This takes a script block that must evaluate to $true, so the sky is the limit. For example:
function Get-Something
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[ValidateScript({ Test-Path $_ -PathType 'Leaf' })]
[ValidateScript({ (Get-Item $_ | select -Expand Extension) -eq ".csv" })]
[string] $Path
)
}
In this example, we are assured not only that $Path exists, but that it is a file, (as opposed to a directory) and has a .csv extension. ($_ refers to the parameter, when inside your scriptblock.) You can also pass in much larger, multi-line script blocks if that level is required, or use multiple scriptblocks like I did here. It's extremely useful and makes for nice clean functions and intuitive exceptions.
You call PowerShell functions without the parentheses and without using the comma as a separator. Try using:
test "ABC" "DEF"
In PowerShell the comma (,) is an array operator, e.g.
$a = "one", "two", "three"
It sets $a to an array with three values.
Function Test([string]$arg1, [string]$arg2)
{
Write-Host "`$arg1 value: $arg1"
Write-Host "`$arg2 value: $arg2"
}
Test "ABC" "DEF"
If you're a C# / Java / C++ / Ruby / Python / Pick-A-Language-From-This-Century developer and you want to call your function with commas, because that's what you've always done, then you need something like this:
$myModule = New-Module -ascustomobject {
function test($arg1, $arg2) {
echo "arg1 = $arg1, and arg2 = $arg2"
}
}
Now call:
$myModule.test("ABC", "DEF")
and you'll see
arg1 = ABC, and arg2 = DEF
Because this is a frequent viewed question, I want to mention that a PowerShell function should use approved verbs (Verb-Noun as the function name).
The verb part of the name identifies the action that the cmdlet performs. The noun part of the name identifies the entity on which the action is performed. This rule simplifies the usage of your cmdlets for advanced PowerShell users.
Also, you can specify things like whether the parameter is mandatory and the position of the parameter:
function Test-Script
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string]$arg1,
[Parameter(Mandatory=$true, Position=1)]
[string]$arg2
)
Write-Host "`$arg1 value: $arg1"
Write-Host "`$arg2 value: $arg2"
}
To pass the parameter to the function you can either use the position:
Test-Script "Hello" "World"
Or you specify the parameter name:
Test-Script -arg1 "Hello" -arg2 "World"
You don't use parentheses like you do when you call a function within C#.
I would recommend to always pass the parameter names when using more than one parameter, since this is more readable.
If you don't know (or care) how many arguments you will be passing to the function, you could also use a very simple approach like;
Code:
function FunctionName()
{
Write-Host $args
}
That would print out all arguments. For example:
FunctionName a b c 1 2 3
Output
a b c 1 2 3
I find this particularly useful when creating functions that use external commands that could have many different (and optional) parameters, but relies on said command to provide feedback on syntax errors, etc.
Here is a another real-world example (creating a function to the tracert command, which I hate having to remember the truncated name);
Code:
Function traceroute
{
Start-Process -FilePath "$env:systemroot\system32\tracert.exe" -ArgumentList $args -NoNewWindow
}
If you try:
PS > Test("ABC", "GHI") ("DEF")
you get:
$arg1 value: ABC GHI
$arg2 value: DEF
So you see that the parentheses separates the parameters
If you try:
PS > $var = "C"
PS > Test ("AB" + $var) "DEF"
you get:
$arg1 value: ABC
$arg2 value: DEF
Now you could find some immediate usefulness of the parentheses - a space will not become a separator for the next parameter - instead you have an eval function.
I don't see it mentioned here, but splatting your arguments is a useful alternative and becomes especially useful if you are building out the arguments to a command dynamically (as opposed to using Invoke-Expression). You can splat with arrays for positional arguments and hashtables for named arguments. Here are some examples:
Note: You can use positional splats with external commands arguments with relative ease, but named splats are less useful with external commands. They work, but the program must accept arguments in the -Key:Value format as each parameter relates to the hashtable key/value pairs. One example of such software is the choco command from the Chocolatey package manager for Windows.
Splat With Arrays (Positional Arguments)
Test-Connection with Positional Arguments
Test-Connection www.google.com localhost
With Array Splatting
$argumentArray = 'www.google.com', 'localhost'
Test-Connection #argumentArray
Note that when splatting, we reference the splatted variable with an # instead of a $. It is the same when using a Hashtable to splat as well.
Splat With Hashtable (Named Arguments)
Test-Connection with Named Arguments
Test-Connection -ComputerName www.google.com -Source localhost
With Hashtable Splatting
$argumentHash = #{
ComputerName = 'www.google.com'
Source = 'localhost'
}
Test-Connection #argumentHash
Splat Positional and Named Arguments Simultaneously
Test-Connection With Both Positional and Named Arguments
Test-Connection www.google.com localhost -Count 1
Splatting Array and Hashtables Together
$argumentHash = #{
Count = 1
}
$argumentArray = 'www.google.com', 'localhost'
Test-Connection #argumentHash #argumentArray
Function Test([string]$arg1, [string]$arg2)
{
Write-Host "`$arg1 value: $arg1"
Write-Host "`$arg2 value: $arg2"
}
Test("ABC") ("DEF")
I don't know what you're doing with the function, but have a look at using the 'param' keyword. It's quite a bit more powerful for passing parameters into a function, and makes it more user friendly. Below is a link to an overly complex article from Microsoft about it. It isn't as complicated as the article makes it sound.
Param Usage
Also, here is an example from a question on this site:
Check it out.
I stated the following earlier:
The common problem is using the singular form $arg, which is incorrect. It should always be plural as $args.
The problem is not that. In fact, $arg can be anything else. The problem was the use of the comma and the parentheses.
I run the following code that worked and the output follows:
Code:
Function Test([string]$var1, [string]$var2)
{
Write-Host "`$var1 value: $var1"
Write-Host "`$var2 value: $var2"
}
Test "ABC" "DEF"
Output:
$var1 value: ABC
$var2 value: DEF
Function Test {
Param([string]$arg1, [string]$arg2)
Write-Host $arg1
Write-Host $arg2
}
This is a proper params declaration.
See about_Functions_Advanced_Parameters.
And it indeed works.
You can pass parameters in a function like this also:
function FunctionName()
{
Param ([string]$ParamName);
# Operations
}

Powershell Switch parameter accepting argument

How can I make $m switch accept one argument but $prebuild doesn't need any argument.
Param (
[Parameter(Mandatory=$true)]
[Switch]$m,
[Switch]$prebuild
)
The script would be executed as below but I get the following error.
.\test.ps1 -m java
A positional parameter cannot be found that accepts argument 'java'
Change $m to a [string]:
param(
[string]$m,
[switch]$prebuild
)
To test whether an argument was passed by the caller, use the $PSBoundParameters automatic variable:
if($PSBoundParameters.ContainsKey('m')){
# An argument was passed to `-m`
}
(This last part is unnecessary if you keep the [Parameter(Mandatory=$true)] attribute)

How to check Number of arguments in powershell?

param (
[string]$Name = $args[0],#First argument will be the adapter name
[IPAddress]$IP = $args[1],#Second argument will be the IP address
[string]$InterfaceId = $args[3],#Second argument will be the IP address
[string]$VlanId = $args[4], #Fourth argument will be vlanid
[string]$SubnetIP = $args[5],#subnet mask
[string]$IPType = "IPv4",
[string]$Type = "Static"
)
Write-Host $Args.Count
I want to check if command line arguments are supplied to the powershell script or not and if its not supplied then i want to show the usage by write. I am running the script in admin mode. I found one method after searching that using $Args.Count we can get the arguments count while running the script but its always zero for me. what am i doing wrong?
enter image description here
Get rid of the $args[x] assignments and add [cmdletbinding()] on top.
[CmdLetbinding()]
param (
[string]$Name, #First argument will be the adapter name
[IPAddress]$IP, # etc...
[string]$InterfaceId,
[string]$VlanId,
[string]$SubnetIP,
[string]$IPType = "IPv4",
[string]$Type = "Static"
)
Then you can use $PSBoundParameters.Count to get the argument count.
$args is a special variable that is used when named parameter are not present.
Therefore, since you have named parameter, it will always give you a count of zero (except maybe if you add more arguments than there is named parameters)
If you use a param block, then you don't need to assign $args[0] and others. In fact, this is totally useless as they will be $null.
The other approach, although I recommend you to keep the param block, is to not use any named parameters at all. In that case, $args will work as you expect it to.
[string]$Name = $args[0]
[IPAddress]$IP = $args[1]
[string]$InterfaceId = $args[3]
[string]$VlanId = $args[4]
[string]$SubnetIP = $args[5]
[string]$IPType = "IPv4"
[string]$Type = "Static"
The main difference is that if you have a param block, you can call your script in the following ways:
.\MyScript.ps1 -Name "Hello" -Ip 127.0.0.1
.\MyScript.ps1 "Hello" 127.0.0.1
Without the param block, you have only option #2 available to call the script.

How to call Jenkins API and send custom parameter with powershell [duplicate]

If I have a function which accepts more than one string parameter, the first parameter seems to get all the data assigned to it, and remaining parameters are passed in as empty.
A quick test script:
Function Test([string]$arg1, [string]$arg2)
{
Write-Host "`$arg1 value: $arg1"
Write-Host "`$arg2 value: $arg2"
}
Test("ABC", "DEF")
The output generated is
$arg1 value: ABC DEF
$arg2 value:
The correct output should be:
$arg1 value: ABC
$arg2 value: DEF
This seems to be consistent between v1 and v2 on multiple machines, so obviously, I'm doing something wrong. Can anyone point out exactly what?
Parameters in calls to functions in PowerShell (all versions) are space-separated, not comma separated. Also, the parentheses are entirely unneccessary and will cause a parse error in PowerShell 2.0 (or later) if Set-StrictMode -Version 2 or higher is active. Parenthesised arguments are used in .NET methods only.
function foo($a, $b, $c) {
"a: $a; b: $b; c: $c"
}
ps> foo 1 2 3
a: 1; b: 2; c: 3
The correct answer has already been provided, but this issue seems prevalent enough to warrant some additional details for those wanting to understand the subtleties.
I would have added this just as a comment, but I wanted to include an illustration--I tore this off my quick reference chart on PowerShell functions. This assumes function f's signature is f($a, $b, $c):
Thus, one can call a function with space-separated positional parameters or order-independent named parameters. The other pitfalls reveal that you need to be cognizant of commas, parentheses, and white space.
For further reading, see my article Down the Rabbit Hole: A Study in PowerShell Pipelines, Functions, and Parameters. The article contains a link to the quick reference/wall chart as well.
There are some good answers here, but I wanted to point out a couple of other things. Function parameters are actually a place where PowerShell shines. For example, you can have either named or positional parameters in advanced functions like so:
function Get-Something
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $Name,
[Parameter(Mandatory=$true, Position=1)]
[int] $Id
)
}
Then you could either call it by specifying the parameter name, or you could just use positional parameters, since you explicitly defined them. So either of these would work:
Get-Something -Id 34 -Name "Blah"
Get-Something "Blah" 34
The first example works even though Name is provided second, because we explicitly used the parameter name. The second example works based on position though, so Name would need to be first. When possible, I always try to define positions so both options are available.
PowerShell also has the ability to define parameter sets. It uses this in place of method overloading, and again is quite useful:
function Get-Something
{
[CmdletBinding(DefaultParameterSetName='Name')]
Param
(
[Parameter(Mandatory=$true, Position=0, ParameterSetName='Name')]
[string] $Name,
[Parameter(Mandatory=$true, Position=0, ParameterSetName='Id')]
[int] $Id
)
}
Now the function will either take a name, or an id, but not both. You can use them positionally, or by name. Since they are a different type, PowerShell will figure it out. So all of these would work:
Get-Something "some name"
Get-Something 23
Get-Something -Name "some name"
Get-Something -Id 23
You can also assign additional parameters to the various parameter sets. (That was a pretty basic example obviously.) Inside of the function, you can determine which parameter set was used with the $PsCmdlet.ParameterSetName property. For example:
if($PsCmdlet.ParameterSetName -eq "Name")
{
Write-Host "Doing something with name here"
}
Then, on a related side note, there is also parameter validation in PowerShell. This is one of my favorite PowerShell features, and it makes the code inside your functions very clean. There are numerous validations you can use. A couple of examples are:
function Get-Something
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[ValidatePattern('^Some.*')]
[string] $Name,
[Parameter(Mandatory=$true, Position=1)]
[ValidateRange(10,100)]
[int] $Id
)
}
In the first example, ValidatePattern accepts a regular expression that assures the supplied parameter matches what you're expecting. If it doesn't, an intuitive exception is thrown, telling you exactly what is wrong. So in that example, 'Something' would work fine, but 'Summer' wouldn't pass validation.
ValidateRange ensures that the parameter value is in between the range you expect for an integer. So 10 or 99 would work, but 101 would throw an exception.
Another useful one is ValidateSet, which allows you to explicitly define an array of acceptable values. If something else is entered, an exception will be thrown. There are others as well, but probably the most useful one is ValidateScript. This takes a script block that must evaluate to $true, so the sky is the limit. For example:
function Get-Something
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[ValidateScript({ Test-Path $_ -PathType 'Leaf' })]
[ValidateScript({ (Get-Item $_ | select -Expand Extension) -eq ".csv" })]
[string] $Path
)
}
In this example, we are assured not only that $Path exists, but that it is a file, (as opposed to a directory) and has a .csv extension. ($_ refers to the parameter, when inside your scriptblock.) You can also pass in much larger, multi-line script blocks if that level is required, or use multiple scriptblocks like I did here. It's extremely useful and makes for nice clean functions and intuitive exceptions.
You call PowerShell functions without the parentheses and without using the comma as a separator. Try using:
test "ABC" "DEF"
In PowerShell the comma (,) is an array operator, e.g.
$a = "one", "two", "three"
It sets $a to an array with three values.
Function Test([string]$arg1, [string]$arg2)
{
Write-Host "`$arg1 value: $arg1"
Write-Host "`$arg2 value: $arg2"
}
Test "ABC" "DEF"
If you're a C# / Java / C++ / Ruby / Python / Pick-A-Language-From-This-Century developer and you want to call your function with commas, because that's what you've always done, then you need something like this:
$myModule = New-Module -ascustomobject {
function test($arg1, $arg2) {
echo "arg1 = $arg1, and arg2 = $arg2"
}
}
Now call:
$myModule.test("ABC", "DEF")
and you'll see
arg1 = ABC, and arg2 = DEF
Because this is a frequent viewed question, I want to mention that a PowerShell function should use approved verbs (Verb-Noun as the function name).
The verb part of the name identifies the action that the cmdlet performs. The noun part of the name identifies the entity on which the action is performed. This rule simplifies the usage of your cmdlets for advanced PowerShell users.
Also, you can specify things like whether the parameter is mandatory and the position of the parameter:
function Test-Script
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string]$arg1,
[Parameter(Mandatory=$true, Position=1)]
[string]$arg2
)
Write-Host "`$arg1 value: $arg1"
Write-Host "`$arg2 value: $arg2"
}
To pass the parameter to the function you can either use the position:
Test-Script "Hello" "World"
Or you specify the parameter name:
Test-Script -arg1 "Hello" -arg2 "World"
You don't use parentheses like you do when you call a function within C#.
I would recommend to always pass the parameter names when using more than one parameter, since this is more readable.
If you don't know (or care) how many arguments you will be passing to the function, you could also use a very simple approach like;
Code:
function FunctionName()
{
Write-Host $args
}
That would print out all arguments. For example:
FunctionName a b c 1 2 3
Output
a b c 1 2 3
I find this particularly useful when creating functions that use external commands that could have many different (and optional) parameters, but relies on said command to provide feedback on syntax errors, etc.
Here is a another real-world example (creating a function to the tracert command, which I hate having to remember the truncated name);
Code:
Function traceroute
{
Start-Process -FilePath "$env:systemroot\system32\tracert.exe" -ArgumentList $args -NoNewWindow
}
If you try:
PS > Test("ABC", "GHI") ("DEF")
you get:
$arg1 value: ABC GHI
$arg2 value: DEF
So you see that the parentheses separates the parameters
If you try:
PS > $var = "C"
PS > Test ("AB" + $var) "DEF"
you get:
$arg1 value: ABC
$arg2 value: DEF
Now you could find some immediate usefulness of the parentheses - a space will not become a separator for the next parameter - instead you have an eval function.
I don't see it mentioned here, but splatting your arguments is a useful alternative and becomes especially useful if you are building out the arguments to a command dynamically (as opposed to using Invoke-Expression). You can splat with arrays for positional arguments and hashtables for named arguments. Here are some examples:
Note: You can use positional splats with external commands arguments with relative ease, but named splats are less useful with external commands. They work, but the program must accept arguments in the -Key:Value format as each parameter relates to the hashtable key/value pairs. One example of such software is the choco command from the Chocolatey package manager for Windows.
Splat With Arrays (Positional Arguments)
Test-Connection with Positional Arguments
Test-Connection www.google.com localhost
With Array Splatting
$argumentArray = 'www.google.com', 'localhost'
Test-Connection #argumentArray
Note that when splatting, we reference the splatted variable with an # instead of a $. It is the same when using a Hashtable to splat as well.
Splat With Hashtable (Named Arguments)
Test-Connection with Named Arguments
Test-Connection -ComputerName www.google.com -Source localhost
With Hashtable Splatting
$argumentHash = #{
ComputerName = 'www.google.com'
Source = 'localhost'
}
Test-Connection #argumentHash
Splat Positional and Named Arguments Simultaneously
Test-Connection With Both Positional and Named Arguments
Test-Connection www.google.com localhost -Count 1
Splatting Array and Hashtables Together
$argumentHash = #{
Count = 1
}
$argumentArray = 'www.google.com', 'localhost'
Test-Connection #argumentHash #argumentArray
Function Test([string]$arg1, [string]$arg2)
{
Write-Host "`$arg1 value: $arg1"
Write-Host "`$arg2 value: $arg2"
}
Test("ABC") ("DEF")
I don't know what you're doing with the function, but have a look at using the 'param' keyword. It's quite a bit more powerful for passing parameters into a function, and makes it more user friendly. Below is a link to an overly complex article from Microsoft about it. It isn't as complicated as the article makes it sound.
Param Usage
Also, here is an example from a question on this site:
Check it out.
I stated the following earlier:
The common problem is using the singular form $arg, which is incorrect. It should always be plural as $args.
The problem is not that. In fact, $arg can be anything else. The problem was the use of the comma and the parentheses.
I run the following code that worked and the output follows:
Code:
Function Test([string]$var1, [string]$var2)
{
Write-Host "`$var1 value: $var1"
Write-Host "`$var2 value: $var2"
}
Test "ABC" "DEF"
Output:
$var1 value: ABC
$var2 value: DEF
Function Test {
Param([string]$arg1, [string]$arg2)
Write-Host $arg1
Write-Host $arg2
}
This is a proper params declaration.
See about_Functions_Advanced_Parameters.
And it indeed works.
You can pass parameters in a function like this also:
function FunctionName()
{
Param ([string]$ParamName);
# Operations
}

How to pass a switch parameter to another PowerShell script?

I have two PowerShell scripts, which have switch parameters:
compile-tool1.ps1:
[CmdletBinding()]
param(
[switch]$VHDL2008
)
Write-Host "VHDL-2008 is enabled: $VHDL2008"
compile.ps1:
[CmdletBinding()]
param(
[switch]$VHDL2008
)
if (-not $VHDL2008)
{ compile-tool1.ps1 }
else
{ compile-tool1.ps1 -VHDL2008 }
How can I pass a switch parameter to another PowerShell script, without writing big if..then..else or case statements?
I don't want to convert the parameter $VHDL2008 of compile-tool1.ps1 to type bool, because, both scripts are front-end scripts (used by users). The latter one is a high-level wrapper for multiple compile-tool*.ps1 scripts.
You can specify $true or $false on a switch using the colon-syntax:
compile-tool1.ps1 -VHDL2008:$true
compile-tool1.ps1 -VHDL2008:$false
So just pass the actual value:
compile-tool1.ps1 -VHDL2008:$VHDL2008
Try
compile-tool1.ps1 -VHDL2008:$VHDL2008.IsPresent
Assuming you were iterating on development, it is highly likely that at some point you are going to add other switches and parameters to your main script that are going to be passed down to the next called script. Using the previous responses, you would have to go find each call and rewrite the line each time you add a parameter. In such case, you can avoid the overhead by doing the following,
.\compile-tool1.ps1 $($PSBoundParameters.GetEnumerator() | ForEach-Object {"-$($_.Key) $($_.Value)"})
The automatic variable $PSBoundParameters is a hashtable containing the parameters explicitly passed to the script.
Please note that script.ps1 -SomeSwitch is equivalent to script.ps1 -SomeSwitch $true and script.ps1 is equivalent to script.ps1 -SomeSwitch $false. Hence, including the switch set to false is equivalent to not including it.
According to a power shell team's blog (link below,) since V2 there is a technique called splatting. Basically, you use the automatic variable #PsBoundParameters to forward all the parameters. Details about splatting and the difference between # and $ are explained in the Microsoft Docs article (link below.)
Example:
parent.ps1
#Begin of parent.ps1
param(
[Switch] $MySwitch
)
Import-Module .\child.psm1
Call-Child #psBoundParameters
#End of parent.ps1
child.psm1
# Begin of child.psm1
function Call-Child {
param(
[switch] $MySwitch
)
if ($MySwitch){
Write-Output "`$MySwitch was specified"
} else {
Write-Output "`$MySwitch is missing"
}
}
#End of child.psm1
Now we can call the parent script with or without the switch
PS V:\sof\splatting> .\parent.ps1
$MySwitch is missing
PS V:\sof\splatting> .\parent.ps1 -MySwitch
$MySwitch was specified
PS V:\sof\splatting>
Update
In my original answer, I sourced the children instead of importing it as a module. It appears sourcing another script into the original just makes the parent's variables visible to all children so this will also work:
# Begin of child.ps1
function Call-Child {
if ($MySwitch){
Write-Output "`$MySwitch was specified"
} else {
Write-Output "`$MySwitch is missing"
}
}
#End of child.ps1
with
#Begin of parent.ps1
param(
[Switch] $MySwitch
)
. .\child.ps1
Call-Child # Not even specifying #psBoundParameters
#End of parent.ps1
Maybe, this is not the best way to make a program, nevertheless, this is the way it works.
About Splatting(Microsoft Docs)
How and Why to Use Splatting (passing [switch] parameters)
Another solution. If you declare your parameter with a default value of $false:
[switch] $VHDL2008 = $false
Then the following (the -VHDL2008 option with no value) will set $VHDL2008 to $true:
compile-tool1.ps1 -VHDL2008
If instead you omit the -VHDL2008 option, then this forces $VHDL2008 to use the default $false value:
compile-tool1.ps1
These examples are useful when calling a Powershell script from a bat script, as it is tricky to pass a $true/$false bool from bat to Powershell, because the bat will try to convert the bool to a string, resulting in the error:
Cannot process argument transformation on parameter 'VHDL2008'.
Cannot convert value "System.String" to type "System.Management.Automation.SwitchParameter".
Boolean parameters accept only Boolean values and numbers, such as $True, $False, 1 or 0.