【问题标题】:Pass parameter from a batch file to a PowerShell script将参数从批处理文件传递到 PowerShell 脚本
【发布时间】:2011-09-15 14:54:20
【问题描述】:
在我的批处理文件中,我这样调用 PowerShell 脚本:
powershell.exe "& "G:\Karan\PowerShell_Scripts\START_DEV.ps1"
现在,我想将一个字符串参数传递给START_DEV.ps1。假设参数是w=Dev。
我该怎么做?
【问题讨论】:
标签:
powershell
batch-file
【解决方案1】:
假设您想从批处理文件中将字符串 Dev 作为参数传递:
powershell -command "G:\Karan\PowerShell_Scripts\START_DEV.ps1 Dev"
放入你的powershell脚本头:
$w = $args[0] # $w would be set to "Dev"
如果你想使用内置变量$args,这个。否则:
powershell -command "G:\Karan\PowerShell_Scripts\START_DEV.ps1 -Environment \"Dev\""
在你的 powershell 脚本头中:
param([string]$Environment)
如果你想要一个命名参数的话。
您可能还对返回错误级别感兴趣:
powershell -command "G:\Karan\PowerShell_Scripts\START_DEV.ps1 Dev; exit $LASTEXITCODE"
错误级别将在批处理文件中显示为%errorlevel%。
【解决方案2】:
假设您的脚本类似于下面的 sn-p 并命名为 testargs.ps1
param ([string]$w)
Write-Output $w
您可以在命令行中调用它:
PowerShell.Exe -File C:\scripts\testargs.ps1 "Test String"
这将在控制台打印“测试字符串”(不带引号)。 “测试字符串”成为脚本中 $w 的值。
【解决方案3】:
加载脚本时,任何传递的参数都会自动加载到特殊变量$args。您可以在脚本中引用它而无需先声明它。
作为示例,创建一个名为 test.ps1 的文件,并将变量 $args 单独放在一行中。像这样调用脚本,会生成以下输出:
PowerShell.exe -File test.ps1 a b c "Easy as one, two, three"
a
b
c
Easy as one, two, three
作为一般建议,当通过直接调用 PowerShell 调用脚本时,我建议使用 -File 选项而不是使用 & 隐式调用它 - 它可以使命令行更简洁,特别是如果您需要处理嵌套引号。
【解决方案4】:
在ps1文件顶部添加参数声明
test.ps1
param(
# Our preferred encoding
[parameter(Mandatory=$false)]
[ValidateSet("UTF8","Unicode","UTF7","ASCII","UTF32","BigEndianUnicode")]
[string]$Encoding = "UTF8"
)
write ("Encoding : {0}" -f $Encoding)
结果
C:\temp> .\test.ps1 -Encoding ASCII
Encoding : ASCII
【解决方案5】:
@Emiliano 的回答非常好。你也可以像这样传递命名参数:
powershell.exe -Command 'G:\Karan\PowerShell_Scripts\START_DEV.ps1' -NamedParam1 "SomeDataA" -NamedParam2 "SomeData2"
注意参数在命令调用之外,你将使用:
[parameter(Mandatory=$false)]
[string]$NamedParam1,
[parameter(Mandatory=$false)]
[string]$NamedParam2