How to pass 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 do not get the expected results if I run it in a separate instance of powershell, for example, powershell -file .\ParameterTest.ps1 (1..10) . In this case, I get the following:

 Password : 3 Login : 2 Integers : {1} 

My question is how to pass an array or other complex data type from the command line?

+4
source share
2 answers

The answer is to use powershell.exe -EncodedCommand and base64 to encode the parameters. The description for this is on the PowerShell.exe Console Help page. I squeezed their version of the ceremony to make it single-line:

 powershell.exe -EncodedCommand "$([Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes('.\ParameterTest.ps1 (1..10)')))" 
+2
source

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

An alternative could be the following:

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

For a version that works with both powershell and cmd:

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

All Articles