1

I am trying to figure out how to populate an unknown number of variables based on user input (writing a script that obtains certificates from a CA, and sometimes these certificates contain more than one name (SANs) and it is impossible to know how many so this needs to be dynamic).

I know I start with setting up params like this:

[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[string[]]$SANs
)

And then I need to somehow take those values and assign them to $san1, $san2, $san3 and so on.

Being new to programming, I am not even sure what to call this. Would you use a foreach loop to somehow populate these variables?

ForEach ($SAN in $SANs) {

what do I do here?

}

The end result is a need to populate a string with these variables like dns=$san1&dns=$san2&dns=$san3 etc...

Dominic Brunetti
  • 989
  • 3
  • 18
  • 36
  • Possible duplicate of [Passing multiple values to a single PowerShell script parameter](https://stackoverflow.com/questions/15120597/passing-multiple-values-to-a-single-powershell-script-parameter) – Bill_Stewart May 10 '18 at 18:38
  • The `$SAN` in your `foreach` would act as each individual item. Ex: Inside your `foreach` put `Write-Host $SAN` this will hopefully give you a better understanding on what is going on. – jrider May 10 '18 at 18:38
  • 1
    So, you're trying to do `'dns=' + ($SANs -join 'dns=')` right? – TheMadTechnician May 10 '18 at 18:45
  • Honestly I just put the `$SAN` variable right inline with the text (I'm making an output text/inf file that will be used to generate the request). Like this: `_continue_ = "dns=$SAN"`r` – Dominic Brunetti May 10 '18 at 18:49
  • @TheMadTechnician only the `&` is missing from the `'dns=' + ($SANs -join '&dns=')` ;-) –  May 10 '18 at 19:25

1 Answers1

4

Functions and scripts can take parameters. The parameter block in your example looked like...

function foo {
    Param([string[]]$SANs)
}

That parameter, $SANs, is an array of strings. A single string would look like this...

$stuff = 'barf'

An array of strings looks like this...

$stuff = @('barf', 'toot', 'ruff', 'meow')

So far so good? If you need to get each of the things in the array, you'd use a loop...

foreach ($thing in $stuff) { write-output $thing }

...for example...

$san_declaration

foreach ($thing in $stuff) {
  if ($san_declaration.length -eq 0) {
    $san_declaration = "dns=${thing}"
  } else {
    $san_declaration += "&dns=${thing}"
  }
}

Now, if you (not that you asked) happen to be calling Get-Certificate, just remember the SANs parameter is a string array. In that case, you'd just pass in the string array instead of creating the string like you were doing.

Get-Certificate -DnsName $stuff
Adam
  • 3,891
  • 3
  • 19
  • 42