Print all positional arguments in PowerShell - powershell

I'm trying to write a PowerShell function that prints out all its arguments.
ArgChecker.ps1
function Print-Args
{
[CmdletBinding()]
param ([string[]]$words)
Write-Verbose "Count: $($words.Count)"
Write-Output "Passed arguments:"
$words
}
I'd also like to call it from a command prompt.
I'm doing it like this
powershell -ExecutionPolicy Bypass -command "& { . .\ArgChecker.ps1; Print-Args 'hi' 'Two' -Verbose }"
but it is throwing an error Print-Args : A positional parameter cannot be found that accepts argument 'Two'.
Is there any way to write the function so that it can accept an unlimited amount of parameters in that format? I think I'm looking for something similar to the params keyword from C#.

In regular functions, you can use the $args automatic variable.
function Write-Args {
$args
}
If you need a cmdlet with CmdletBinding, you can use the ValueFromRemainingArguments option:
function Write-Args {
[CmdletBinding()]
param(
[Parameter(ValueFromRemainingArguments)]
[string[]]$Arguments
)
$Arguments
}
Note however, because of the CmdletBinding, -Verbose will not appear in that list, because it's a common parameter. If you want to list those too, you could use the $PSBoundParameters automatic variable.

Related

Passing scriptblock as an argument to Invoke-Command scriptblock in powershell

I have a powershell script in which I have been trying to pass scriptblock(i.e $sb) as an argument to another scriptblock. However, I keep getting error that:
Cannot convert the "{get-member}" value of type "System.String" to
type "System.Management.Automation.ScriptBlock
a.psm1:
$sb = {get-member}
# $type = $sb.GetType().FullName => Returns scriptblock as data type
$result = Invoke-Command -Session "DC" -Scriptblock
{
Param(
[Parameter(Mandatory=$true)]
[scriptblock]
$sb
)
//Do some task
} -ArgumentList $sb
I am not able to figure out why $sb is treated as a string instead of Scriptblock?
The only way it works is changing the argument inside the Invoke-Command scriptblock to be of type string instead of Scriptblock.
I am not sure why scriptblocks gets implicitly converted to string while passing argument to Invoke-Command scriptblock.
When a script block (type [scriptblock], { ... } as a literal) is passed to code that executes out-of-process, such as during remoting (your case) or in background jobs, XML-based serialization and deserialization must be performed.
On deserialization in the target process, [scriptblock] instances indeed unexpectedly become strings.
Unfortunately and bewilderingly, this behavior has been declared by design(!) - see GitHub issue #11698.
Your only option is to pass the script block('s source code) as a string, and convert it back to a script block via [scriptblock]::Create(); a simple example, using a background job:
Start-Job {
param([string] $scriptBlockSourceCode) # Note the type: [string]
# Use [scriptblock]::Create() to turn the string into a script block,
# and execute it with &
& ([scriptblock]::Create($scriptBlockSourceCode))
} -ArgumentList { 'hi' } |
Receive-Job -Wait -AutoRemove

Passing hashtable and args to powershell invoke-command as arguments

Normally one can do the following:
function example{
param(
$Parameter1,
$Parameter2
)
"Parameter1: $Parameter1"
"Parameter2: $Parameter2"
$PSBoundParameters
$args
}
and pass parameters explicitly or by splatting like so:
$options = #{parameter1='bounded parameter'}
example #options -Parameter2 'will be bounded too' 'this will go into args' -Parameter3 'this will too','and this one also'
Parameter1: bounded parameter
Parameter2: will be bounded too
Key Value
--- -----
Parameter1 bounded parameters
Parameter2 will be bounded too
this will go into args
-Parameter3
this will too
and this one also
I would like to replicate that syntax's behavior somehow when using invoke command.
Ideally somethings like this syntax:
$options = #{parameter1='bounded parameter';parameter3='this will too'}
Invoke-Command -Computername REMOTESERVER -ArgumentList #options 'will be bounded to parameter2' 'this will go into args', 'and this one also' -ScriptBlock {'block'}
I have seen this answer:
https://stackoverflow.com/a/36283506/12603110 suggesting to wrap the script block with 👇 which allows splatting of hashtables
{param($Options)& <# Original script block (including {} braces)#> #options }
I'm unsure how to deal with the $args and explicitly specified parameters(e.g. Parameter2).
Nothing stops you from deconstructing, modifying and then proxying the arguments received by Invoke-Command:
$options = #{parameter1='bounded parameter'}
Invoke-Command -ArgumentList $options, "some other param", "unbound stuff" -ScriptBlock {
# extract splatting table from original args list
$splat,$args = $args
& {
param($Parameter1, $Parameter2)
"Parameter1: $Parameter1"
"Parameter2: $Parameter2"
$PSBoundParameters
$args
} #splat #args
}

How to pass all flags in a Powershell New-Alias?

I'm using C:\Users\User\Documents\Powershell\Microsoft.PowerShell_profile.ps1 for some alias commands for my every day work.
Example:
function MyAliasCommand { .\custom\script.ps1 }
New-Alias my MyAliasCommand
It works if I call it from my Powershell using the command "my".
I'm happy.
What it doesn't work is if I need to pass flags to my, example:
my -d one
How to do this?
Is there a way to let powershell pass all my arguments in the function MyAliasCommand?
Something like: function MyAliasCommand { .\custom\script.ps1 $allTheFlags }?
I would do this as follows:
./custom/script.ps1
[CmdletBinding()]
param (
[Parameter()]
[string]
$d
)
Write-Host $d
Then you can write:
function MyCommand {
& $PSScriptRoot/custom/script.ps1 #args
}
New-Alias myAlias MyCommand
myAlias -d 'one'
Take into account that I used the call operator and splatting.
$args will contain all the parameters you supply.

Default value of parameter is not used in function

I have a very basic PowerShell script:
Param(
[string]$MyWord
)
function myfunc([string] $MyWord) {
Write-Host "$MyWord"
}
myfunc #PSBoundParameters
This is how I execute it:
PS C:\> .\test.ps1 -MyWord 'hello'
hello
All fine. But I want to set a default value if -MyWord isn't specified.
I tried this:
Param(
[string]$MyWord='hi'
)
function myfunc([string] $MyWord) {
Write-Host "$MyWord"
}
myfunc #PSBoundParameters
But than the output of my script was just empty. It was printing nothing when I did not describe my parameter. (it only showed 'hello' if I specified the parameter).
I also tried:
Param(
[string]$MyWord
)
function myfunc([string] $MyWord) {
[string]$MyWord='hi'
Write-Host "$MyWord"
}
myfunc #PSBoundParameters
But than the output was of course always 'hi' and never 'hello'. Even when I executed the script with the parameter -MyWord 'hello'
Can someone explaining what I'm doing wrong?
When I'm not using the function it is working as expected:
Param(
[string]$MyWord='hi'
)
Write-Host $MyWord
Output:
PS C:\> .\test.ps1 -MyWord 'hallo'
hallo
PS C:\> .\test.ps1
hi
Automatic variable $PSBoundParameters, as the name suggests, contains only bound parameters, where bound means that an actual value was supplied by the caller.
Therefore, a parameter default value does not qualify as binding the associated parameter, so $MyWord with its default value of 'hi' does not become part of $PSBoundParameters.
Note: Arguably, a parameter with a default value should also be considered bound (it is bound by its default value, as opposed to by a caller-supplied value). Either way, it would be convenient to have an automatic variable that includes default values too, so as to enable simple and comprehensive passing through of arguments. A suggestion has been submitted to the PowerShell repository as GitHub issue #3285.
Workarounds
The following solutions assume that you want to pass the default value through, and don't want to simply duplicate the default value in function myfunc (as demonstrated in Ansgar Wiecher's helpful answer), because that creates a maintenance burden.
Regarding function syntax: The following two forms are equivalent (in this case), though you may prefer the latter for consistency and readability.[1]
function myfunc([string] $MyWord = 'hi') { ... }
parameter declaration inside (...) after the function name.
function myfunc { param([string] $MyWord = 'hi') ... }
parameter declaration inside a param(...) block inside the function body.
A simple fix would be to add the default value explicitly to $PSBoundParameters:
Param(
[string]$MyWord = 'hi'
)
function myfunc ([string] $MyWord){
Write-Host "$MyWord"
}
# Add the $MyWord default value to PSBoundParameters.
# If $MyWord was actually bound, this is effectively a no-op.
$PSBoundParameters.MyWord = $MyWord
myfunc #PSBoundParameters
To achieve what you want generically, you must use reflection (introspection):
param(
[alias('foop')]
[string]$MyWord = 'hi'
)
function myfunc ([string] $MyWord) {
Write-Host "$MyWord"
}
# Add all unbound parameters that have default values.
foreach ($paramName in $MyInvocation.MyCommand.Parameters.Keys) {
if (-not $PSBoundParameters.ContainsKey($paramName)) {
$defaultVal = Get-Variable -Scope Local $paramName -ValueOnly
# A default value is identified by either being non-$null or
# by being a [switch] parameter that defaults to $true (which is bad practice).
if (-not ($null -eq $defaultVal -or ($defaultVal -is [switch] -and -not $defaultVal))) {
$PSBoundParameters[$paramName] = $defaultVal
}
}
}
myfunc #PSBoundParameters
[1] The param(...) form is required if you need to use the [CmdletBinding()] attribute with non-default values, as well as in scripts (.ps1). See this answer.
A parameter is bound only if you actually pass it a value, meaning that a parameter's default value does not show up in $PSBoundParameters. If you want to pass script parameters into a function, you must replicate the script parameter set in the function parameter set:
Param(
[string]$MyWord = 'hi'
)
function myfunc([string]$MyWord = 'hi') {
Write-Host "$MyWord"
}
myfunc #PSBoundParameters
Maintaining something like this is easier if you define both parameter sets the same way, though, so I'd put the function parameter definition in a Param() block as well:
Param(
[string]$MyWord = 'hi'
)
function myfunc {
Param(
[string]$MyWord = 'hi'
)
Write-Host "$MyWord"
}
If you want to use "Param" enclose it in the function like this:
function myfunc {
Param(
[string]$MyWord='hi'
)
Write-Host "$MyWord"
}
Very simple way is,
function myfunc([string]$MyWord = "hi") {
Write-Output $MyWord
}

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.