将字符串 $variable 传递给调用命令脚本块参数 -name [英] Passing string $variable to invoke-command scriptblock parameter -name
问题描述
我目前正在编写一个相对简单的 PowerShell 脚本来重新启动/停止/启动远程计算机上的服务.一切正常,直到我决定将 $Service
变量传递给 Invoke-Command
Scriptblock 中的 -Name
参数.我知道我做错了什么或忘记了什么,但您的帮助将不胜感激.这是突出显示问题的部分代码
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" } }
}
我试过了:
- $Service 周围的单引号
- $Service 周围的双引号
- 在脚本块中使用 param([String]$Service)
我一遍又一遍地得到同样的错误:
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
使用这里提到的方法如何将局部变量传递给 Invoke-Command 我修改了代码,如下所示:
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
推荐答案
将参数传递到脚本块的语法应如下所示:
the syntax for parameter passing into a scriptblock should be as follows:
(更正为@pk198105 建议)
(Corrected as @pk198105 suggested)
Invoke-command -Computername $Server {
param($service)
Restart-Service -Name "$Service"
} -ArgumentList $service
argumentlist 和 param 都是必需的
both argumentlist and param are required
这篇关于将字符串 $variable 传递给调用命令脚本块参数 -name的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!