title: Passing string $variable to invoke-command scriptblock parameter -name
body: <p>I'm currently writing a relatively easy PowerShell script to restart/stop/start a service on a remote machine. Everything is working well up until I decide to pass a <code>$Service</code> variable to <code>-Name</code> parameter in the <code>Invoke-Command</code> Scriptblock. I know I'm doing something wrong or forgetting something but your help would be greatly appreciated. Here is the code with the part giving me problems highlighted</p>
  
  <pre><code>[CmdletBinding()] Param([Parameter(Mandatory=$True,Position=1)]
    [string]$Server,
    [Parameter(Mandatory=$True)]
    [string]$Service) 
  get-service -ComputerName $Server -Name "$Service"
  
  Write-Host("------------------------------------------------")
  Write-Host("Execute action on selected service: ")
  Write-Host("1. Restart service ")
  Write-Host("2. Stop service ")
  Write-Host("3. Start service")
  $choice = Read-Host -Prompt "Your choice"
  
  switch ($choice)
  {
      1 {Invoke-command -Computername $Server {Restart-Service -Name "$Service" } }
      2 {Invoke-command -ComputerName $Server {Stop-Service  -Name "$Service" } }
      3 {Invoke-command -ComputerName $Server {Start-Service -Name "$Service" } }
  }
  </code></pre>
  
  <p>I have tried:</p>
  
  <ul>
  <li>Single quotes around $Service</li>
  <li>Double quotes around $Service</li>
  <li>using param([String]$Service) in scriptblock</li>
  </ul>
  
  <p>I keep getting the same error over and over:</p>
  
  <pre><code>Cannot bind argument to parameter 'Name' because it is an empty string.
      + CategoryInfo          : InvalidData: (:) [Stop-Service], ParameterBindingValidationException
      + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.StopServiceCommand
  </code></pre>
  
  <p>I know it has to do with the fact Im trying to run local variable on a remote machine. but could someone point me in the right direction , I would love for the script to simply use the mandatory parameters  </p>
  
  <p>Using the approach mentionned here <a href="https://stackoverflow.com/questions/36339616/">How to pass local variable to Invoke-Command's</a> I modified the code like so:</p>
  
  <pre><code>1 {Invoke-command -Computername $Server {param ([string] $srv = $Service) Restart-Service -Name "$srv" } }
  </code></pre>
  
  <p>Unfortunately the error persists</p>