通过命令行传递变量给PowerShell脚本

58

我是 PowerShell 的新手,正在尝试自学基础知识。我需要编写一个 PS 脚本来解析一个文件,这并不太困难。

现在我想要将它改成可以传递脚本变量的形式。该变量将是解析字符串。现在,该变量始终为一个单词,而不是一组词或多个单词。

这似乎非常简单,但对我来说却很棘手。以下是我的简单代码:

$a = Read-Host
Write-Host $a
当我在命令行中运行脚本时,变量传递不起作用:
.\test.ps1 hello
.\test.ps1 "hello"
.\test.ps1 -a "hello"
.\test.ps1 -a hello
.\test.ps1 -File "hello"

正如您所看到的,我已经尝试了许多方法,但脚本无法将输入值输出。

脚本确实可以运行,并等待我输入值,当我输入值时,它会回显该值。

我只想输出我的传入值,我错过了什么微小的东西?

谢谢。


2
可能是如何在PowerShell中处理命令行参数的重复问题。 - Michael Freidgeim
5个回答

77

在你的 test.ps1 文件的第一行添加以下内容

param(
[string]$a
)

Write-Host $a

然后你可以使用以下方式调用它

./Test.ps1 "Here is your text"

在这里找到了此处英文


我更愿意使用"./Test.ps1 -a="Here is your text""这样的方式进行调用,但它会像这样打印出$a: "-a=Here is your string"。 - Andy
@ozzy432836 我也喜欢那种语法,但它并没有内置到powershell中。如果没有空格,PS会将其视为单个未命名的参数。你当然可以实现自己的参数解析,但你可能要考虑到这不是任何人所期望的。Powershell的内置功能允许使用命名和未命名(又称位置)参数,强制和可选参数具有默认值,并自动生成帮助。因为你(和我)更喜欢“=”而不是空格,所以这是很多东西要丢弃的。我在C#中浪费了时间重新发明这个轮子,但我的用户中很少有人关心。 - Andrew Dennison
将参数写在第一行很重要,因为如果参数不在第一行,就会出现错误。 - Deepak Yadav

56

以下是关于Powershell参数的良好教程:

PowerShell ABC's - P是指参数

基本上,你应该在脚本第一行使用param语句:

param([type]$p1 = , [type]$p2 = , ...)

或者使用$ args内置变量,它会自动填充所有参数。


@MichaelHedgpeth:看起来这是一个暂时性问题;现在已经恢复了。我不知道文章是否有更永久的链接。 - Brian Stephens
1
个人而言,$args参数更容易。 :) - SaundersB
链接又坏了 :-( - Michaël Polla
1
@MichaëlPolla:我希望他们能停止移动这篇文章!我又修复了链接。 - Brian Stephens

13
在test.ps1中声明参数。
Param(
    [Parameter(Mandatory=$True,Position=1)]
    [string]$input_dir,
    [Parameter(Mandatory=$True)]
    [string]$output_dir,
    [switch]$force = $false
)

从Run或Windows任务计划程序中运行脚本。
powershell.exe -command "& C:\FTP_DATA\test.ps1 -input_dir C:\FTP_DATA\IN -output_dir C:\FTP_DATA\OUT"

或者,
powershell.exe -command "& 'C:\FTP DATA\test.ps1' -input_dir 'C:\FTP DATA\IN' -output_dir 'C:\FTP DATA\OUT'"

7

传递以下参数,

Param([parameter(Mandatory=$true,
   HelpMessage="Enter name and key values")]
   $Name,
   $Key)

运行脚本.\script_name.ps1时,需要提供两个参数:namekey


帮助信息是如何出现的? - not2qubit
1
@not2qubit 实际上,如果用户不知道如何执行操作,帮助文本将非常有用。要获取该帮助文本,您需要在不传递任何输入的情况下键入!?。 - kalaivani

3
使用param来命名参数可以忽略参数的顺序:
ParamEx.ps1
# Show how to handle command line parameters in Windows PowerShell
param(
  [string]$FileName,
  [string]$Bogus
)
write-output 'This is param FileName:'+$FileName
write-output 'This is param Bogus:'+$Bogus

ParaEx.bat

rem Notice that named params mean the order of params can be ignored
powershell -File .\ParamEx.ps1 -Bogus FooBar -FileName "c:\windows\notepad.exe"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接