将string$variables传递给invoke-command scriptblock参数-name

我目前正在编写一个相对简单的PowerShell脚本来重启/停止/启动远程机器上的服务。 在我决定在Invoke-Command Scriptblock中将一个$Servicevariables传递给-Name参数之前,一切正常。 我知道我做错了什么或忘记了一些东西,但是你的帮助将不胜感激。 这里是部分代码给我突出的问题

 [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" } } } 

我努力了:

  • $ Service周围的单引号
  • $ Service周围的双引号
  • 在scriptblock中使用param([String] $ Service)

我一直得到相同的错误:

 Cannot bind argument to parameter 'Name' because it is an empty string. + CategoryInfo : InvalidData: (:) [Stop-Service], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.StopServiceCommand 

我知道这与事实我试图在远程机器上运行本地variables。 但是有人能指出我正确的方向,我希望脚本能够简单地使用强制参数

使用这里提到的方法如何将本地variables传递给Invoke-Command的我修改了代码,如下所示:

 1 {Invoke-command -Computername $Server {param ([string] $srv = $Service) Restart-Service -Name "$srv" } } 

不幸的是,错误仍然存​​在

好的,这要归功于Abhijith pk

实现这个的正确方法如下:

 Invoke-command -Computername $server {param ($Service) Restart-Service -Name "$service" } -ArgumentList $service 

谢谢

参数传递到scriptblock的语法应如下所示:

(更正为@ pk198105建议)

 Invoke-command -Computername $server { param($service) Restart-Service -Name "$Service" } -ArgumentList $service 

参数列表和参数都是必需的