将参数传递给PowerShell中开关内调用的函数
运行PowerShell脚本时,我希望根据传递的第一个参数调用函数。为此,我使用了一个开关将参数传递给PowerShell中开关内调用的函数,powershell,Powershell,运行PowerShell脚本时,我希望根据传递的第一个参数调用函数。为此,我使用了一个开关 function veeamScript([string]$command) { switch($command) { install { install #calls a function which doesn't need arguments } create {
function veeamScript([string]$command) {
switch($command)
{
install
{
install #calls a function which doesn't need arguments
}
create
{
create($name, $server, $username, $password)
}
Default
{
echo "The help text"
}
}
}
scriptName($command)
如果我这样调用脚本
scriptName.ps1 create myname myserver theusername thepassword
它应该调用这个函数
function create($name, $server, $username, $password) {
$check=checkIfInstalled # This calls another function which works and is either true or false
if ($check -eq $true)
{
echo "Name: $name"
echo "Server: $server"
echo "Username: $username"
echo "Password: $password"
...
} else
{
echo "ERROR ..."
}
}
但是,回声都是“空的”(例如,在名称之后:)
看起来参数没有通过开关传递,更不用说传递给函数了。在调用函数之前,我在交换机中添加了一个echo,并且echo也是空的
create
{
echo "$name" # Also tried it without the double quotation marks, didn't work
create($name, $server, $username, $password)
}
有人知道我如何调用脚本,让开关决定调用哪个函数(取决于第一个参数)并传递其余参数吗?使用
$args
自动变量和@
splat运算符:
# scriptName.ps1
# split arguments into first,rest
$command,$actualArguments = $args
# check that command name is valid
if($command -in 'create','install')
{
# user provided a valid command name, let's execute it with the remaining args
& $command @actualArguments
}
else
{
# throw an error or show usage text
"Usage: ..."
}
现在,它将同时使用命名参数和位置参数参数,您甚至不需要开关
有关Splating的更多信息,请参见使用
$args
自动变量和@
splat运算符:
# scriptName.ps1
# split arguments into first,rest
$command,$actualArguments = $args
# check that command name is valid
if($command -in 'create','install')
{
# user provided a valid command name, let's execute it with the remaining args
& $command @actualArguments
}
else
{
# throw an error or show usage text
"Usage: ..."
}
现在,它将同时使用命名参数和位置参数参数,您甚至不需要开关
有关Splating的更多信息,请参见调用函数的正确方法是使用空格作为函数及其参数之间的分隔符。这允许正确解析项目-->
创建$name$server$username$password
。在函数调用发生之前,需要在代码中定义函数。话虽如此,由于VeeamScript
只有一个参数,因此在脚本调用中只有create
会被绑定,因为没有引号。调用函数的正确方法是使用空格作为函数及其参数之间的分隔符。这允许正确解析项目-->创建$name$server$username$password
。在函数调用发生之前,需要在代码中定义函数。话虽如此,由于VeeamScript
只有一个参数,因此在脚本调用中只有create
会被绑定,因为没有引号。