如何将数组参数传递给PowerShell -file?

4
我有以下的PowerShell脚本:

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...}

然而,如果我在一个单独的Powershell实例中运行它(例如:powershell -file .\ParameterTest.ps1 (1..10)),我将得不到预期的结果。这种情况下,我会得到以下结果:

Password : 3
Login    : 2
Integers : {1}

我的问题是如何从命令行传递数组或其他复杂数据类型?
2个回答

6

将数组的各个元素(1..10)作为参数传递给脚本。

另一种方法是:

powershell -command {.\test.ps1 (1..10)}

对于同时适用于PowerShell控制台和cmd的版本:

powershell -command "&.\test.ps1 (1..10)"

这比-EncodeCommand更简单,并且也可以在cmd.exe中工作。 - Justin Dearing

2
答案是使用powershell.exe -EncodedCommand并对参数进行base64编码。关于此的描述在PowerShell.exe控制台帮助 technet页面上。我将他们的版本压缩成了一行代码:
powershell.exe -EncodedCommand "$([Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes('.\ParameterTest.ps1 (1..10)')))"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接