Like in C and other languages, you can give to the script/.exe arguments when you physically execute the script. For example:
myScript.exe Hello 10 P
Whereby Hello, 10 and P are passed to some variable in the program itself.
Is this possible in Powershell? and if so, how do you give those args to a given $variable
Thanks!
Define your script with a param block like so:
-- Start of script foo.ps1 --
param($msg, $num, $char)
"You passed in $msg, $num and $char"
You can further type qualify parameters as well e.g:
-- Start of script foo2.ps1 --
param([string]$msg, [int]$num, [char]$char)
"You passed in $msg, $num and $char"
You can also specify default values and required values e.g.:
-- Start of script foo3.ps1 --
param([string]$msg=$(throw "Msg param is required"), [int]$num, [char]$char="P")
"You passed in $msg, $num and $char"
You can get even fancier with advanced functions (specify attributes to validate parameters, etc). But this should get you going.
Just a complement to @Keith Hill answer ...
As you talk about 'C', you can also write a scripts with parameters using the automatic variable $args
.
$Args
Contains an array of the undeclared parameters and/or parameter values that are passed to a function, script, or script block.
-- Start of script foo3.ps1 --
if ($args.length -gt 0)
{
write-host "first param is $($args[0])"
}
for ($i=0 ; $i -lt $args.length ; $i++)
{
write-host "$i) " $args[$i]
}
you can call thr script
.\foo3.ps1 coucou bonjour "hello world"
first param is coucou
0) coucou
1) bonjour
2) hello world
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With