Arguments with Powershell Scripts on Launch

天大地大妈咪最大 提交于 2019-12-05 06:41:04

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!