将参数从批处理文件传递到PowerShell脚本

Kar*_*ran 86 powershell

在我的批处理文件中,我像这样调用PowerShell脚本:

powershell.exe "& "G:\Karan\PowerShell_Scripts\START_DEV.ps1"
Run Code Online (Sandbox Code Playgroud)

现在,我想传递一个字符串参数START_DEV.ps1.让我们说参数是w=Dev.

我怎样才能做到这一点?

Emi*_*ggi 135

powershell -command "G:\Karan\PowerShell_Scripts\START_DEV.ps1 Dev"
Run Code Online (Sandbox Code Playgroud)

在你的脚本头内:

$w=$args[0]
Run Code Online (Sandbox Code Playgroud)

这个如果你想使用内置变量$args.除此以外:

 powershell -command "G:\Karan\PowerShell_Scripts\START_DEV.ps1 -Environment \"Dev\""
Run Code Online (Sandbox Code Playgroud)

在你的脚本头内:

param([string]$Environment)
Run Code Online (Sandbox Code Playgroud)

这个如果你想要一个命名参数.

您可能还有兴趣返回错误级别:

powershell -command "G:\Karan\PowerShell_Scripts\START_DEV.ps1 Dev; exit $LASTEXITCODE"
Run Code Online (Sandbox Code Playgroud)

错误级别将在批处理文件中可用%errorlevel%.


rav*_*nth 22

假设您的脚本类似于以下代码段并命名为testargs.ps1

param ([string]$w)
Write-Output $w
Run Code Online (Sandbox Code Playgroud)

您可以在命令行中将其称为:

PowerShell.Exe -File C:\scripts\testargs.ps1 "Test String"
Run Code Online (Sandbox Code Playgroud)

这将在控制台上打印"测试字符串"(没有引号)."Test String"成为脚本中$ w的值.


Goy*_*uix 11

加载脚本时,传递的任何参数都会自动加载到特殊变量中$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
Run Code Online (Sandbox Code Playgroud)

作为一般建议,当通过直接调用PowerShell调用脚本时,我建议使用该-File选项而不是使用它隐式调用它&- 它可以使命令行更清晰,特别是如果您需要处理嵌套引号.


tec*_*int 8

@Emiliano 的回答非常好。您还可以像这样传递命名参数:

powershell.exe -Command 'G:\Karan\PowerShell_Scripts\START_DEV.ps1' -NamedParam1 "SomeDataA" -NamedParam2 "SomeData2"
Run Code Online (Sandbox Code Playgroud)

请注意参数在命令调用之外,您将使用:

[parameter(Mandatory=$false)]
  [string]$NamedParam1,
[parameter(Mandatory=$false)]
  [string]$NamedParam2
Run Code Online (Sandbox Code Playgroud)


Hyu*_*ang 5

在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)
Run Code Online (Sandbox Code Playgroud)

结果

C:\temp> .\test.ps1 -Encoding ASCII
Encoding : ASCII
Run Code Online (Sandbox Code Playgroud)