通过命令行将变量传递给powershell脚本
Posted
技术标签:
【中文标题】通过命令行将变量传递给powershell脚本【英文标题】:Passing a variable to a powershell script via command line 【发布时间】:2013-05-01 20:35:17 【问题描述】:我是 powershell 新手,正在尝试自学基础知识。我需要写一个ps脚本来解析一个文件,这已经不是太难了。
现在我想更改它以将变量传递给脚本。该变量将是解析字符串。现在,变量将始终为 1 个单词,而不是一组单词或多个单词。
这看起来非常简单,但对我来说却是个问题。这是我的简单代码:
$a = Read-Host
Write-Host $a
当我从命令行运行脚本时,变量传递不起作用:
.\test.ps1 hello
.\test.ps1 "hello"
.\test.ps1 -a "hello"
.\test.ps1 -a hello
.\test.ps1 -File "hello"
如您所见,我尝试了许多方法,但都没有成功,脚本获取值并输出它。
脚本会运行,并等待我输入一个值,当我输入一个值时,它会回显该值。
我只想让它输出我传入的值,我错过了什么小东西?
谢谢。
【问题讨论】:
How to handle command-line arguments in PowerShell的可能重复 【参考方案1】:在你的 test.ps1 的第一行做这个
param(
[string]$a
)
Write-Host $a
然后你可以调用它
./Test.ps1 "Here is your text"
找到here (English)
【讨论】:
我宁愿用 ./Test.ps1 -a="Here is your text" 来调用它,但它会像这样打印 $a:-a=Here is your string @ozzy432836 我也更喜欢这种语法,但它没有内置在 powershell 中。没有空格 PS 将其视为一个未命名的参数。您当然可以实现自己的参数解析,但您可能会认为这不会是其他人所期望的。 Powershell 的内置功能允许命名和未命名(也称为位置)参数、具有默认值的强制和可选参数,并自动生成帮助。这是很多东西要扔掉的,因为你(和我)更喜欢“=”而不是空格。我浪费了时间在 C# 中重新发明了这个***,我的用户很少会关心。 将它写在第一行很重要,因为如果参数不在第一行,它会出错。【参考方案2】:这是一个关于 Powershell 参数的好教程:
PowerShell ABC's - P is for Parameters
基本上,您应该在脚本的第一行上使用param
语句
param([type]$p1 = , [type]$p2 = , ...)
或使用 $args 内置变量,它会自动填充所有参数。
【讨论】:
@MichaelHedgpeth:看起来这是一个暂时的问题;它现在恢复了。我不知道这篇文章的更永久链接。 个人认为 $args 参数比较容易。 :) 链接又断了:-( @MichaëlPolla:我希望他们停止移动文章!我又修复了链接。【参考方案3】:在test.ps1中声明参数:
Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$input_dir,
[Parameter(Mandatory=$True)]
[string]$output_dir,
[switch]$force = $false
)
从 Run OR Windows Task Scheduler 运行脚本:
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'"
【讨论】:
【参考方案4】:传递的参数如下,
Param([parameter(Mandatory=$true,
HelpMessage="Enter name and key values")]
$Name,
$Key)
.\script_name.ps1 -Name name -Key key
【讨论】:
帮助信息是怎么进来的? @not2qubit 实际上,如果用户不知道如何执行,帮助文本将很有用。要获得该帮助文本,您必须输入!?不传递任何输入。【参考方案5】:使用 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"
【讨论】:
以上是关于通过命令行将变量传递给powershell脚本的主要内容,如果未能解决你的问题,请参考以下文章
是否可以通过命令行将 vbscript 数组传递给 C++ exe?