How-to: Pass parameters to a PowerShell script.

Script Parameters / Arguments (for scripts, functions and script blocks)

Pass arguments to a script or cmdlet by separating them with spaces:

PS C:\> Get-ChildItem -Path $env:windir -Filter *.dll -Recurse

This can be made a little more readable by breaking up long lines with PowerShell’s escape character:

PS C:\> Get-ChildItem `
  -Path "$env:windir" `
  -Filter *.dll `
  -Recurse

To pass multiple arguments to a script you can splat them:

$myargs = @{
   Path = "$env:windir"
   filter = '*.dll
   Recurse = $true
}
Get-ChildItem @myargs

The above will be expanded to: Get-ChildItem -Path $env:windir -Filter *.dll -Recurse

Enclose strings inside double-quotes, and any variables inside will be expanded.

$args

Within a script or function you can refer to unnamed arguments using the $args array, for example passing all the arguments through to a cmdlet. You can also refer to specific arguments by their position:

"First argument is " + $Args[0]
"Second argument is " + $Args[1]

So if you call the script above like ./demoscript.ps1 "Alpha" "Beta", it will return:
"First argument is Alpha
"Second argument is Beta

The $args array only contains the values for undeclared parameters, so this approach will only work in a non-advanced function or script.

Param

To define arguments by name, use a param statement, which is a comma separated list of variables, optionally prefixed with a [data type] and/or with = default values.

If used, the param statement MUST be the first thing in your script or function:

param (
   [string]$welcome
)

Then call the script/function like:

mysuperfunction -welcome "Hello world"

A more complex example with multiple parameters, separated with commmas and some default values:

param (
   [string]$welcome, 
   [string]$ComputerName = $env:computername,    
   [string]$username = $(throw "-username is required."),
   [string]$password = $( Read-Host -asSecureString "Input password" ),
   [switch]$SaveData = $false
)

write-output "The price is $price"
write-output "The Computer Name is $ComputerName"
write-output "The True/False switch argument is $SaveData"

Calling this script, and setting the switch parameter -SaveData to $TRUE:
.\demo.ps1 -ComputerName "\\server64" -SaveData

or setting -SaveData to $FALSE:
.\demo.ps1 -ComputerName "\\server64" -SaveData:$false

Defaults in PowerShell 3.0 and above

In PowerShell 3.0 if an arguments default value is omitted, there is an implied default value of $true you can use this to shorten both params and parameter attributes, (n.b. leaving out the = $true in this way will prevent the script from running in PowerShell 1.0 or 2.0)

Param (
   [Parameter(ValueFromPipelineByPropertyName)]
   [string] $DemoParameter
)

Parameter Attributes

In an Advanced Function, the params statement block can also optionally define parameter attributes:

[Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] 

These affect the function parameters as follows:

Mandatory - Whether the parameter is mandatory or optional (the default)

ValueFromPipeline - Accept values via the pipeline, of the same type expected by the parameter or that can be converted to the type that the parameter is expecting.

ValueFromPipelineByPropertyName - Accept values via the pipeline of the same type expected by the parameter and which also must have the same name as the parameter accepting pipeline input.

An Advanced Function is one that contains either a [cmdletbinding()] attribute or the Parameter attribute, or both.

cmdletbinding adds several capabilities such as additional parameter checking, and the ability to easily use Write-Verbose.
A function with cmdletbinding will throw an error if unhandled parameter values appear on the command line.

Drag and Drop

To pass file or folder names into a PowerShell script with drag and drop, use the 'ValueFromRemainingArguments' parameter:

[CmdletBinding()]
param (
  [Parameter(ValueFromRemainingArguments=$true)] $Path
)
"The file or folder(s) you dragged and dropped are:"
$Path

Call the above with a one line batch file, then to run, drag and drop files or folders onto the batch file:

@Echo off
pwsh.exe -noexit -file c:\scripts\demo.ps1 %*

or for pre-powershell 6:

@Echo off
powershell.exe -noexit -file c:\scripts\demo.ps1 %*

Cmdlet Parameters

Almost every PowerShell cmdlet can accept one or more optional parameters which can be supplied on the command line in the form -Parameter_Name Parameter_Value

The name of the parameter is always preceded by a hyphen (-)

The Parameter_value often needs to be provided in a specific data type (e.g. string or integer)
To find these details use Get-Help -detailed cmdletName

In some cases, the Parameter_Name is implied and does not need to be explicitly included.

In syntax descriptions:

 [-Param] -- is optional 
  -Param  -- is required

If you exclude the Parameter Names you must ensure that the Parameter Values are listed in the correct order (assuming more than one value is being passed .)

Parameter Names will be ignored if contained in quotation marks.

Multiple values (for the same parameter) can be separated with commas.

Parameters for external commands

When calling a non-PowerShell command or CMD utility then the parameters won’t follow any PowerShell conventions,

Generally any arguments to external commands should be surrounded in quotes if needed due to spaces/long filenames (just like the CMD shell) or if any part of the command uses characters that have a special meaning to PowerShell such as brackets ( ) or { } s

See the & CALL operator page for more ways to execute a command, script or function.

“Slow down and enjoy life. It’s not only the scenery you miss by going too fast, you also miss the sense of where you are going and why” ~ Eddie Cantor

Related PowerShell Cmdlets

help about_Functions_Advanced_Parameters
$PSBoundParameters -
Advanced Functions - Adding ValidateSet and Help, a function template to copy.
Common parameters - Cmdlet parameters that you can use with any cmdlet.
& (call) - Run a command, script or function.
Pipelines - Pass objects down the pipeline.
Wildcards - Match multiple items.


 
Copyright © 1999-2024 SS64.com
Some rights reserved