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...

5
  • Possible duplicate of Passing multiple values to a single PowerShell script parameter Commented May 10, 2018 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. Commented May 10, 2018 at 18:38
  • 1
    So, you're trying to do 'dns=' + ($SANs -join 'dns=') right? Commented May 10, 2018 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` Commented May 10, 2018 at 18:49
  • @TheMadTechnician only the & is missing from the 'dns=' + ($SANs -join '&dns=') ;-) Commented May 10, 2018 at 19:25

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

This worked perfectly. Marked as answer. Thank you for the thorough explanation.
My pleasure botha.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.