powershell - How to loop through arrays in hash table - passing parameters based on values read from a CSV file -
curious how loop through hash table each value array. example:
$test = @{ = "a","1"; b = "b","2"; c = "c","3"; }
then like:
foreach ($t in $test) { write-output $t }
expected result like:
name value b b c c 1 b 2 c 3
that's not happens , use case pass hash of parameters function in loop. approach might wrong, figured ask , see if anyone's tried this?
edit** bit more clarification. i'm trying pass lot of array values function , loop through in hash table prior passing nested function. example:
first like:
$parameters = import-csv .\newcomputers.csv
then like
$parameters | new-labvm
lab vm code below:
function new-labvm { [cmdletbinding()] param ( # param1 description [parameter(mandatory=$true, position=0, valuefrompipeline=$true, valuefrompipelinebypropertyname=$true)] [alias("p1")] [string[]]$servername, # param2 description [parameter(position = 1)] [int[]]$ram = 2gb, # param3 description [parameter(position=2)] [int[]]$serverharddrivesize = 40gb, # parameter description [parameter(position=3)] [int[]]$vmrootpath = "d:\virtualmachines", [parameter(position=4)] [int[]]$networkswitch = "vm switch 1", [parameter(position=4)] [int[]]$iso = "d:\iso\win2k12.iso" ) process { new-item -path $vmrootpath\$servername -itemtype directory $arguments = @{ name = $servername; memorystartupbytes = $ram; newvhdpath = "$vmrootpath\$servername\$servername.vhdx"; newvhdsizebytes = $serverharddrivesize switchname = $networkswitch;} foreach ($argument in $arguments){ # create virtual machines new-vm @arguments # configure virtual machines set-vmdvddrive -vmname $servername -path $iso start-vm $servername } # create virtual machines new-vm @arguments } }
what you're looking parameter splatting.
the robust way via hashtables, must convert custom-object instances output import-csv
hashtables:
import-csv .\newcomputers.csv | foreach-object { # convert custom object @ hand hashtable. $htparams = @{} $_.psobject.properties | foreach-object { $htparams[$_.name] = $_.value } # pass hashtable via splatting (@) target function. new-labvm @htparams }
note since parameter binding via splatting key-based (the hashtable keys matched against parameter names), fine use regular hashtable unpredictable key ordering (no need ordered hashtable ([ordered] @{ ... }
) in case).
Comments
Post a Comment