There are multiple ways you can pass arguments in a PowerShell script. You can use param to pass parameters to your script or access the passed argument by position with the system variable $args[]. Let’s explain with an example
Using args[]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
## Using argument position (args[]) ## Create a script that prints argument passed echo @' echo "This is 1st argument: " $args[0] echo "This is 2nd argument: " $args[1] '@ > myscript.ps1 ## Execute the script with arguments .\myscript.ps1 "hello" "world" ## Returns ## This is 1st argument: ## hello ## This is 2nd argument: ## world |
Using param
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
## Using argument name (param) ## Update the script to use parameter name echo @' Param( [Parameter(Mandatory, HelpMessage="You must enter parameter woth -arg1 name")] [string[]] $para1, [Parameter(Mandatory, HelpMessage="You must enter parameter woth -arg2 name")] [string[]] $para2 ) echo "This is 1st argument: " $para1 echo "This is 2nd argument: " $para2 '@ > myscript.ps1 ## Execute the script with arguments .\myscript.ps1 -para1 "hello" -para2 "world" ## Returns ## This is 1st argument: ## hello ## This is 2nd argument: ## world |