在我的批处理文件中,我这样调用PowerShell脚本:
powershell.exe "& "G:\Karan\PowerShell_Scripts\START_DEV.ps1"
现在,我想要传递一个字符串参数给START_DEV.ps1
。假设这个参数是w=Dev
。
我该如何实现呢?
在我的批处理文件中,我这样调用PowerShell脚本:
powershell.exe "& "G:\Karan\PowerShell_Scripts\START_DEV.ps1"
现在,我想要传递一个字符串参数给START_DEV.ps1
。假设这个参数是w=Dev
。
我该如何实现呢?
假设你想从批处理文件中传递字符串参数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%
在批处理文件中可用。
param ([string]$w)
Write-Output $w
你可以在命令行中调用此命令:
PowerShell.Exe -File C:\scripts\testargs.ps1 "Test String"
这将在控制台打印“Test String”(不带引号)。 “Test String”成为脚本中$w的值。
$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
选项而不是隐式地使用&
来调用 - 这样可以使命令行更加清晰,特别是如果需要处理嵌套引号。
@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
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