harryjohn
harryjohn

Reputation: 686

How can I pass dynamic parameters to powershell script and iterate over the list?

I want to create a powershell script that accepts dynamic parameters and I also want to iterate through them.

eg: I call the powershell script in the following manner.

ParametersTest.ps1 -param1 value1 -param2 value2 -param3 value3

And I should be able to access my params inside the script as follows:

for($key in DynamicParams) {
    $paramValue = DynamicParams[$key];
}

Is there anyway to do this in powershell? Thanks in advance.

Upvotes: 2

Views: 2354

Answers (1)

Joey
Joey

Reputation: 354694

There is nothing built-in like that (essentially you're asking for PowerShell parameter parsing in the absence of any definition of those parameters). You can emulate it, though. With $args you can get at all arguments of the function as an array. You can then iterate that and decompose it into names and values:

$DynamicParams = @{}
switch -Regex ($args) {
  '^-' {
    # Parameter name
    if ($name) {
      $DynamicParams[$name] = $value
      $name = $value = $null
    }
    $name = $_ -replace '^-'
  }
  '^[^-]' {
    # Value
    $value = $_
  }
}
if ($name) {
  $DynamicParams[$name] = $value
  $name = $value = $null
}

To iterate over dynamic parameters you can either do something like you wrote

foreach ($key in $DynamicParams.Keys) {
  $value = $DynamicParams[$key]
}

(note the foreach, not for, the latter of which cannot work like you wrote it) or just iterate normally over the hash table:

$DynamicParams.GetEnumerator() | ForEach-Object {
  $name = $_.Key
  $value = $_.Value
}

Upvotes: 2

Related Questions