如何将数组参数传递给powershell-file?
我有以下powershell脚本:如何将数组参数传递给powershell-file?,powershell,command-line,Powershell,Command Line,我有以下powershell脚本: param( [Int32[]] $SomeInts = $null, [String]$User = "SomeUser", [String]$Password = "SomePassword" ) New-Object PSObject -Property @{ Integers = $SomeInts; Login = $User; Password = $Password; } | Format-L
param(
[Int32[]] $SomeInts = $null,
[String]$User = "SomeUser",
[String]$Password = "SomePassword"
)
New-Object PSObject -Property @{
Integers = $SomeInts;
Login = $User;
Password = $Password;
} | Format-List
如果我执行\ParameterTest.ps1(1..10)
我会得到以下结果:
Password : SomePassword
Login : SomeUser
Integers : {1, 2, 3, 4...}
Password : 3
Login : 2
Integers : {1}
但是,如果在单独的powershell实例中运行它,则不会得到预期的结果,例如powershell-file。\ParameterTest.ps1(1..10)
。在这种情况下,我得到以下结果:
Password : SomePassword
Login : SomeUser
Integers : {1, 2, 3, 4...}
Password : 3
Login : 2
Integers : {1}
我的问题是如何从命令行传递数组或其他复杂数据类型?答案是使用
powershell.exe-EncodedCommand
并对参数进行base64编码。technet页面上有对此的说明。我将他们的仪式版本压缩为一行:
powershell.exe -EncodedCommand "$([Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes('.\ParameterTest.ps1 (1..10)')))"
数组的各个元素(
1..10
)作为参数传递给脚本
另一种选择是:
powershell -command {.\test.ps1 (1..10)}
对于同时从powershell控制台和cmd运行的版本:
powershell -command "&.\test.ps1 (1..10)"
这比-encode命令更简单,也可以从cmd.exe运行。