Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass an array parameter to powershell -file?

I have the following powershell script:

param(
    [Int32[]] $SomeInts = $null, 
    [String]$User = "SomeUser", 
    [String]$Password = "SomePassword"
)

New-Object PSObject -Property @{
    Integers = $SomeInts;
    Login = $User;
    Password = $Password;
} | Format-List

If I execute .\ParameterTest.ps1 (1..10) I get the following:

Password : SomePassword
Login    : SomeUser
Integers : {1, 2, 3, 4...}

However, I don't get the expected results if I run it in a separate powershell instance like this powershell -file .\ParameterTest.ps1 (1..10). In that case I get the following:

Password : 3
Login    : 2
Integers : {1}

My question is how can I pass the array, or other complex data type from a command line?

like image 399
Justin Dearing Avatar asked Feb 22 '23 19:02

Justin Dearing


2 Answers

The individual elements of the array (1..10) are being passed as parameters to the script.

An alternative would be to do:

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

For a version that works both from powershell console and cmd:

powershell -command "&.\test.ps1 (1..10)"
like image 111
manojlds Avatar answered Mar 03 '23 03:03

manojlds


The answer is to use powershell.exe -EncodedCommand and to base64 encode the parameters. The description for this is on the PowerShell.exe Console Help technet page. I have compressed their version of the ceremony to do this into a one-liner:

powershell.exe -EncodedCommand "$([Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes('.\ParameterTest.ps1 (1..10)')))"
like image 20
Justin Dearing Avatar answered Mar 03 '23 03:03

Justin Dearing