1

I'm getting this error message:

The variable '$server' cannot be retrieved because it has not been set.

The error occurs at the beginning of the switch statement below:

function Get-ServerName {
   [Parameter(mandatory)] [TARGET_SERVER] $server
<#
.SYNOPSIS
Retrieves the name of the SFTP server running on on the user’s computer.
.PARAMETER server
The server type whose name we want.
.OUTPUTS
The folder (“Undefined” if null)
#>
   switch ($server) {
      local   { $key = $LOCAL_HOST_NAME_KEY     }
      remote  { $key = $REMOTE_HOST_NAME_KEY    }
      default { Deny-ServerType -server $server }
   }

The data type TARGET_SERVER is defined like this:

enum TARGET_SERVER { # Server receiving the uploaded files
   remote            # The server hosting the public-facing Web site
   local             # An SFTP server running on the user’s computer. Used for testing.
}

The function is called like this:

$hostName = Get-ServerName -server $server

I’ve verified that $server IS set to “local,” so I can't understand what's causing the error.

How do I fix this?

mklement0
  • 382,024
  • 64
  • 607
  • 775
aksarben
  • 588
  • 3
  • 7
  • 1
    you're missing a `param` block. in addition, you're setting the parameter as `Mandatory` but in your `enum` you're only allowing `local` or `remote` so the `default` block in your `switch` would never be hit – Santiago Squarzon Jul 18 '23 at 19:42
  • As Santiago notes, parameter declarations in PowerShell functions and scripts must be enclosed in `param(...)`. Unfortunately, not doing so currently causes the parameters to be _quietly ignored_. [GitHub issue #10614](https://github.com/PowerShell/PowerShell/issues/10614) suggests improving the handling of such cases. – mklement0 Jul 18 '23 at 20:15
  • That's just what I was thinking. PowersShell should have pointed out the bad syntax instead of giving that cryptic error text. – aksarben Jul 18 '23 at 23:59

1 Answers1

1

Oops. Just realized I forgot to enclose the parameter like this

 param ([Parameter(mandatory)] [TARGET_SERVER]$server)
aksarben
  • 588
  • 3
  • 7
  • Please don't use the answer box for non-answers. Click the [Edit link](https://stackoverflow.com/posts/76715997/edit) under your question and update the original code sample instead. – Mathias R. Jessen Jul 18 '23 at 19:43
  • @MathiasR.Jessen, this actually _is_ the answer: the problem was the missing `param(...)` enclosure around the parameter definition. – mklement0 Jul 18 '23 at 20:08