我目前正在编写一个相对简单的PowerShell脚本来重新启动/停止/启动远程机器上的服务。一切都工作得很好,直到我决定将$Service
变量传递给Invoke-Command
Scriptblock中的-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" } }
}
I have try:
- $Service 单引号
- $Service 双引号
- 使用参数([String]$Service)在scriptblock
我一直得到相同的错误一遍又一遍:
Cannot bind argument to parameter 'Name' because it is an empty string.
+ CategoryInfo : InvalidData: (:) [Stop-Service], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.StopServiceCommand
我知道这与我试图在远程机器上运行本地变量有关。但是有人可以指出我在正确的方向,我希望脚本简单地使用强制性参数
使用这里提到的方法如何将局部变量传递给调用命令,我将代码修改如下:
1 {Invoke-command -Computername $Server {param ([string] $srv = $Service) Restart-Service -Name "$srv" } }
不幸的是,错误仍然存在
传递给scriptblock的参数的语法应该如下:
(更正为@pk198105建议)
Invoke-command -Computername $Server {
param($service)
Restart-Service -Name "$Service"
} -ArgumentList $service
argumentlist和param都是必需的
ok部分归功于Abhijith pk
正确的实现方法如下:
Invoke-command -Computername $Server {param ($Service) Restart-Service -Name "$service" } -ArgumentList $service
谢谢