Passing an array as a parameter in PowerShell
arrays, dictionary, powershell
Solution
I think this boils down to when you are being prompted for the input (by not specifying the value for the parameter on the command line) it is being read in a similar manner to using the `Read-Host` cmdlet. The output of that cmdlet is either a `[System.String]` or `[System.Security.SecureString]`.
As such, instead of the input to the script/function being a proper object, it is just a long string. You can see the difference if you add a debug line to your script just after the param() block:
Write-Debug ($Array | Out-String)
You will need to set `$DebugPreference="Continue"` on the console, before you run the script, to view debug output. When you run the script, you should see the difference it makes using the prompted input.
- Read-Host
Personally I wouldn't try much harder to collect "complex" data from the console prompt and look at ways to make sure you feed in the data on the command line, as you have already tried.
Problem
I'm having some trouble with Powershell, I have code that looks like this: ``` param ( [Parameter(Mandatory=$true)] $Array = '' ) foreach ($member in $Array){ Write-Host "TEST" $server = $member["server"] $path = $member["path"] $key = $member["key"] Write-Host $server Write-Host $path Write-Host $key } ``` When I provide the following line as input, the script only prints "TEST" and nothing further, but when I define `$Array` within the script itself with the exact same code, the script works as expected. ``` @(@{"server" = "server1"; "path" = "\\path1"; "key" = "key1"}, @{"server" = "server2"; "path" = "\\path2"; "key" = "key2"}, @{"server" = "server3"; "path" = "\\path3"; "key" = "key3"}) ``` The expected output is: ``` TEST server1 \\path1 key1 TEST server2 \\path2 key2 TEST server3 \\path3 key3 ``` This is my first reach into PowerShell coming from a Python background. It seems that if this array is passed at the command line level, it works. However, if the script prompts for the input and it's entered at that point, it fails. Where am I going wrong? To clarify, the below code works perfectly well, with each key's value being printed to the console. ``` $Array = @(@{"server" = "server1"; "path" = "\\path1"; "key" = "key1"}, @{"server" = "server2"; "path" = "\\path2"; "key" = "key2"}, @{"server" = "server3"; "path" = "\\path3"; "key" = "key3"}) foreach ($member in $Array){ Write-Host "TEST" $server = $member["server"] $path = $member["path"] $key = $member["key"] Write-Host $server Write-Host $path Write-Host $key } ```