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

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

问题描述

多年来,我使用了 cmd / DOS / Windows shell并传递命令行参数到批处理文件。例如,我有一个文件 zuzu.bat ,在其中,我访问%1 %2 等等。现在,当我调用 PowerShell 脚本时,在Cmd.exe shell 中。我有一个脚本, xuxu.ps1 (我已经添加PS1到我的PATHEXT变量和相关的PS1文件与PowerShell)。但是不管我做什么,我似乎不能从 $ args 变量获得任何东西。



如果我在一个 PowerShell shell中,而不是 cmd.exe ,它工作(当然)。但我还不够舒服,全天候住在PowerShell环境中。我不想键入 powershell.exe -command xuxu.ps1 p1 p2 p3 p4 。我想键入 xuxu p1 p2 p3 p4



这是否可以,如果是,如何?



我无法工作的样本很简单, foo.ps1:

 写主机Num Args:$ args.Length; 
foreach($ args中的$ arg){
Write-HostArg:$ arg;
}

结果总是这样:

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


解决方案

本文有帮助。特别是此部分:



-File

本地作用域(点源),以便脚本创建的函数和变量在当前会话中可用。输入脚本文件路径和任何参数。文件必须是命令中的最后一个参数,因为在File参数名称后键入的所有字符都将解释为脚本文件路径,后跟脚本参数。


ie

  powershell.exe -FileC:\myfile.ps1arg1 arg2 arg3 

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


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.

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?

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";
}

The results are always like this:

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:

-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.

i.e.

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

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

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

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