question

MrFlinstone-1451 avatar image
0 Votes"
MrFlinstone-1451 asked RichMatheisen-8856 edited

passing a key value pair list to a powershell script

Hi All.

I would like to write a PS script file that will accept a list that consists of a value pair.

The 2 parameters should be passed as a multi valued array, $id and $name
The idea is that I then want to process each value within the script using a foreach loop to print out each ID and each name.


param([string[]]$id_key_pair = $(throw "Please enter id and name as a pair"))

windows-server-powershell
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

IanXue-MSFT avatar image
0 Votes"
IanXue-MSFT answered

Hi,

Why not pass a hashtable to the script?

 Param(
     [Parameter(Mandatory=$True, Position=0)]
     [Hashtable]
     $id_key_pair = $(throw "Please enter id and name as a pair"))
 )
 $id_key_pair 

Best Regards,
Ian Xue
============================================
If the Answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

RichMatheisen-8856 avatar image
0 Votes"
RichMatheisen-8856 answered RichMatheisen-8856 edited

If you prefer to us an array instead of a hash, you can use this:

 function keypairs{
     param( [string[]]$id_key_pair = $(throw "Please enter ids and names as a comma-separated pair"))
    
     if ($id_key_pair.count % 2){
         Write-Host "You must pass an even number of values"
          return
     }
     for ($i=0;$i -lt $id_key_pair.count; $i = $i + 2){
         "{0} = {1}" -f $id_key_pair[$i], $id_key_pair[$i+1]
     }
 }
    
 keypairs 1,'a',2,'b',3,'c',4,'d'
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.