command-line - 如何将命令行参数传递给 PowerShell ps1 文件

标签 command-line powershell arguments

多年来,我一直使用 cmd/DOS/Windows shell 并将命令行参数传递给批处理文件。例如,我有一个文件 zuzu.bat,在其中我访问 %1%2 等。现在,我想要当我在 Cmd.exe shell 中调用 PowerShell 脚本时执行相同的操作。我有一个脚本 xuxu.ps1 (我已将 PS1 添加到我的 PATHEXT 变量中,并使用 PowerShell 关联 PS1 文件)。但无论我做什么,我似乎都无法从 $args 变量中获取任何内容。它的长度始终为 0。

如果我使用的是 PowerShell shell,而不是 cmd.exe,它就可以工作(当然)。但我还不太适应全职生活在 PowerShell 环境中。我不想输入 powershell.exe -command xuxu.ps1 p1 p2 p3 p4。我想输入 xuxu p1 p2 p3 p4

这可能吗?如果可能的话,如何实现?

我无法开始工作的示例很简单,foo.ps1:

Write-Host "Num Args:" $args.Length;
foreach ($arg in $args) {
    Write-Host "Arg: $arg";
}

结果总是这样的:

C:\temp> foo
Num Args: 0
C:\temp> foo a b c d
Num Args: 0
c:\temp>

最佳答案

This article有帮助。特别是本节:

-File

Runs the specified script in the local scope ("dot-sourced"), so that the functions and variables that the script creates are available in the current session. Enter the script file path and any parameters. File must be the last parameter in the command, because all characters typed after the File parameter name are interpreted as the script file path followed by the script parameters.

powershell.exe -File "C:\myfile.ps1" arg1 arg2 arg3

表示运行文件 myfile.ps1 和 arg1 arg2 和 arg3 是 PowerShell 脚本的参数。

关于command-line - 如何将命令行参数传递给 PowerShell ps1 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1293907/

相关文章:

web-services - 从命令行调用 REST WS

ios - 解析iOS SDK : Setting up Cloud Code in Terminal

windows - 使用 powershell 更改注册表二进制数据

c++ - 将 char * 作为函数参数传递时出现意外行为

input - Golang - 检查参数数量?还有用户输入 - 检查返回键(空行)条目 ""

r - 对 R 术语 : Attributes, 参数和参数感到困惑

command-line - Vagrant 提供实时输出

command-line - 命令历史的 Cygwin 快捷方式

string - PowerShell字符串串联给出了换行符

.net - PowerShell:加载程序集时创建事件处理程序