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

批处理中,可以将传递的参数与%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
}

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

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

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
  • 您可以使用comment-based help记录参数及其用法
本文链接:https://www.f2er.com/3094314.html

大家都在问