在Powershell中是否有用于传递参数的动态变量?

问题描述 投票:0回答:2

批处理中,传递的参数可以与%1一起使用,并且可以继续计数。可以说我有以下“ batch.bat”脚本:

@ echo off
echo %1
pause>nul

如果我从cmd调用此命令,例如:call batch.bat hello,它将在控制台中输出“ hello”。

ps中是否有做相同事情的变量?

编辑

我发现有胡言乱语,但似乎有点不自然。

$CommandLine = "-File `"" + $MyInvocation.MyCommand.Path + "`" " + $MyInvocation.UnboundArguments
Start-Process -FilePath PowerShell.exe -Verb Runas -ArgumentList $CommandLine
Exit
}

也许还有更优雅的东西吗?

powershell arguments parameter-passing
2个回答
1
投票

PowerShell具有automatic variable $args,用于存储传递给脚本的所有参数(除非为脚本定义了参数)。可以通过索引访问各个参数(第一个参数为$args[0],第二个参数为$args[1],依此类推。)>

但是,通常建议define parameters控制脚本应接受的参数,例如

[CmdletBinding()]
Param(
    [Parameter(Mandatory=$true)]
    [string]$First,

    [Parameter(Mandatory=$false)]
    [integer]$Second = 42
)

具有很多优点,包括(但不限于):

  • 脚本提示输入强制性参数
  • 如果传递了错误的参数,脚本将引发错误
  • 您可以为可选参数定义默认值
  • 您可以让您的脚本或函数接受管道输入
  • 您可以validate parameter values
  • 您可以使用基于注释的帮助来记录参数及其用法

0
投票

根据@ Kamil-leis的建议查找$args

© www.soinside.com 2019 - 2024. All rights reserved.