【问题标题】:What is powershell equivalent to "%*" in cmd? [duplicate]什么是 cmd 中相当于“%*”的powershell? [复制]
【发布时间】:2018-05-27 21:39:18
【问题描述】:
如何在 powershell 函数中编写以下 cmd 脚本:
@echo off
C:\bin\command.exe %*
Powershell 脚本:
function f{
[CmdletBinding()] Param()
# .. Code? ...
}
【问题讨论】:
标签:
powershell
batch-file
cmd
scripting
【解决方案1】:
如果您想定义一个param 块并仍然捕获所有参数,您可以定义一个使用Parameter 属性上的ValueFromRemainingArguments 参数的参数。
function Test-Function {
[CmdletBinding()]
param(
[string] $FirstParameter,
[Parameter(ValueFromRemainingArguments=$true)]
[object[]] $RemainingArguments
)
end {
$PSBoundParameters
}
}
Test-Function first and then the rest go to remaining
# Key Value
# --- -----
# FirstParameter first
# RemainingArguments {and, then, the, rest...}
【解决方案2】:
使用Param() 定义,您不能有未绑定的参数(编辑: 除非您定义一个参数来捕获所有未绑定的参数,如Patrick Meinecke 在他的回答中指出的那样)。传递给函数的所有参数都必须在 Param() 块中定义,否则 PowerShell 将抛出 InvalidArgument 异常。然后将参数列在字典 $MyInvocation.BoundParameters 中。
如果没有Param() 定义,函数的所有参数都列在自动变量$args(以及$MyInvocation.UnboundArguments)中。
【解决方案3】:
重复的帖子提供了很好的参考,但没有直接回答手头的问题。
将批次与 PS 进行比较:
PShell 提供了更多的命令行信息,因为它是基于对象的。
-
这个等式可以简化事情。
$MyInvocation.line =
$MyInvocation.InvocationName +
$MyInvocation.MyCommand +
[$MyInvocation.BoundParameters | $MyInvocation.UnboundArguments ]
$MyInvocation.line entire string used to invoke script or
function.
$MyInvocation.InvocationName if present could be & (Call) or . (DotSource)
$MyInvocation.MyCommand Name of the script.
$MyInvocation.BoundParameters Variables in the param () parentheses.
$MyInvocation.UnboundArguments Command-Line variables not in parentheses.
%* 将匹配绑定或未绑定的参数。由于您有一个空参数 (),您将使用 unbound。
function f{
[CmdletBinding()] Param()
& C:\bin\command.exe "$(($MyInvocation).UnboundArguments)"
}
来源
How to get all arguments passed to function (vs. optional only $args)
PowerShell 命令行帮助 about_automatic_variables