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 $Service
variable to -Name
parameter in the Invoke-Command
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
[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" } }
}
I have tried:
- Single quotes around $Service
- Double quotes around $Service
- using param([String]$Service) in scriptblock
I keep getting the same error over and over:
Cannot bind argument to parameter 'Name' because it is an empty string.
+ CategoryInfo : InvalidData: (:) [Stop-Service], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.StopServiceCommand
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
Using the approach mentionned here How to pass local variable to Invoke-Command's I modified the code like so:
1 {Invoke-command -Computername $Server {param ([string] $srv = $Service) Restart-Service -Name "$srv" } }
Unfortunately the error persists