0

I have two variables, $audience and $prodType that will hold value of 1-3 and 1-4 respectively. I'd like to build a table of sorts to convert the numeric values into words that a user can read and understand. For example, if $audience = '1' I would like the script to Write-Host "audience is set to New York" and if $prodType = '3', the script would Write-Host "prodType is set to Sandwiches".

I would like a cleaner way to do this then a series of elseif statements.

If($audience = '1'){
  Write-Host "audience is set to New York"
}
elseif($audience = '2'){
  Write-Host "audience is set to Los Angeles"
}

Can anyone help me build such a module?

1 Answer 1

3

There's a number of ways to achieve this, but based on your scenario the easiest is with hashtables:

$audienceLocation = @{
  '1' = 'New York'
  '2' = 'Berlin'
  '3' = 'Beijing' 
}

$audience = '1'

Write-Host "audience is set to $($audienceLocation[$audience])"

In your case the input values are all strings - but if they were numerical and you didn't mind converting to a string label without spaces, an enum type would be an option as well.

Enums are just collections of string labels associated with some underlying integer, and can be converted in either direction with a simple cast:

enum AudienceLocation
{
  NewYork = 1
  Berlin  = 2
  Beijing = 3
}

$audience = 1
$location = [AudienceLocation]$audience

Write-Host "audience is set to $location"

The nice thing about an enum is that it's a proper type, so you can implicitly convert function input to a specific enum type parameter:

function Do-Something
{
  param([AudienceLocation]$Audience)

  Write-Host "audience is set to $Audience"
}

Do-Something -Audience 1 # will automatically turn `$Audience` into `'NewYork"` in a string
Sign up to request clarification or add additional context in comments.

3 Comments

Ah the @{} is what i needed. Does that function have a name?
@Garrett That's a [hashtable] literal. Hash tables are basically unordered (and super-fast) dictionaries. Will update the answer with a link to documentation
I've never used enum, going to keep this thread for future reference, looks super helpful. Thanks for all the great info!

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.