<分区>
我目前正在编写一个相对简单的 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" } }
}
我试过:
- $Service 单引号
- $Service 双引号
- 在脚本 block 中使用 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
我知道这与我试图在远程机器上运行本地变量有关。但是有人能给我指明正确的方向吗,我希望脚本能够简单地使用强制参数
使用这里提到的方法 How to pass local variable to Invoke-Command's我像这样修改了代码:
1 {Invoke-command -Computername $Server {param ([string] $srv = $Service) Restart-Service -Name "$srv" } }
不幸的是,错误仍然存在