如何将命令行参数传递给 PowerShell ps1 文件 [英] How to pass command-line arguments to a PowerShell ps1 file

查看:50
本文介绍了如何将命令行参数传递给 PowerShell ps1 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For years, I have used the cmd/DOS/Windows shell and passed command-line arguments to batch files. For example, I have a file, zuzu.bat and in it, I access %1, %2, etc. Now, I want to do the same when I call a PowerShell script when I am in a Cmd.exe shell. I have a script, xuxu.ps1 (and I've added PS1 to my PATHEXT variable and associated PS1 files with PowerShell). But no matter what I do, I seem unable to get anything from the $args variable. It always has length 0.

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

If I am in a PowerShell shell, instead of cmd.exe, it works (of course). But I'm not yet comfortable enough to live in the PowerShell environment full time. I don't want to type powershell.exe -command xuxu.ps1 p1 p2 p3 p4. I want to type xuxu p1 p2 p3 p4.

这可能吗,如果可能,怎么做?

Is this possible, and if so, how?

我无法开始工作的示例是微不足道的,foo.ps1:

The sample I cannot get to work is trivial, 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 helps. In particular, this section:

-文件

在本地范围内运行指定的脚本(dot-sourced"),以便脚本创建的函数和变量在当前会话中可用.输入脚本文件路径和任何参数.File 必须是命令中的最后一个参数,因为在 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 脚本的参数.

means run the file myfile.ps1 and arg1 arg2 & arg3 are the parameters for the PowerShell script.

这篇关于如何将命令行参数传递给 PowerShell ps1 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆