如何通过命令行参数来一个PowerShell PS1文件 [英] How to pass command-line arguments to a PowerShell ps1 file

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

问题描述

多年来,我已经使用了 CMD / DOS / Windows的的外壳,并通过命令行参数的批处理文件。例如,我有一个文件, zuzu.bat ,并在其中,我访问%1 %2 等。现在,我想,当我称之为的PowerShell 剧本当我做同样的在外壳的Cmd.exe 。我有一个脚本, xuxu.ps1 (我已经添加PS1到我的PATHEXT变量和相关的PS1文件使用PowerShell)。但无论我做什么,我似乎无法得到从的$ args 变量什么。它总是长度为0。

如果我在的PowerShell 的外壳,而不是的cmd.exe ,它的作品(当然)。但我还没有足够舒适生活在PowerShell中的环境全职。我不想键入 powershell.exe -command xuxu.ps1 P1 P2 P3 P4 。我要键入栩栩P1 P2 P3 P4

这是可能的,如果是这样,怎么样?

我不能获得工作的样品是微不足道的,foo.ps1:

 写主机民参数数量:$ args.Length;
的foreach(在的$ args $ ARG){
    写主机精氨酸:$ ARG
}

结果总是这样的:

  C:\\ TEMP>富
民参数数量:0
C:\\ TEMP> foo的A B C D
民参数数量:0
C:\\ TEMP>


解决方案

确定,所以首先这是打破在PowerShell中一个基本的安全功能。了解这一点,这里是你如何能做到这一点:


  1. 打开一个的Windows 资源管理器窗口

  2. 菜单的工具的 - >的文件夹选项的 - >标签的文件类型

  3. 找到的PS1文件类型,然后单击高级按钮

  4. 单击新建按钮

  5. 有关行动提出:打开

  6. 对于应用程序放:C:\\ WINNT \\ SYSTEM32 \\ WindowsPowerShell \\ V1.0 \\ powershell.exe-file%1%*

您可能希望把 -NoProfile 论点也有根据您的个人资料做什么。

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>

解决方案

OK, so first this is breaking a basic security feature in PowerShell. With that understanding, here is how you can do it:

  1. Open an Windows Explorer window
  2. Menu Tools -> Folder Options -> tab File Types
  3. Find the PS1 file type and click the advanced button
  4. Click the New button
  5. For Action put: Open
  6. For the Application put: "C:\WINNT\system32\WindowsPowerShell\v1.0\powershell.exe" "-file" "%1" %*

You may want to put a -NoProfile argument in there too depending on what your profile does.

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

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