我正在尝试使用此Powershell脚本停止远程服务:
$hostname1 = "myhost"
$serviceName = "myservice"
Write-Host "Hostname: $hostname1"
Write-Host "Service name: $serviceName"
Invoke-Command -ComputerName $hostname1 -ScriptBlock {
Stop-Service -Name $serviceName -Force
}
但收到此错误消息:
Cannot bind argument to parameter 'Name' because it is null.
+ CategoryInfo : InvalidData: (:) [Stop-Service], ParameterBindin
gValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,M icrosoft.PowerShell.Commands.StopServiceCommand
如果我从脚本中删除Invoke-Command
,我可以看到变量已正确初始化:
$hostname1 = "myhost"
$serviceName = "myservice"
Write-Host "Hostname: $hostname1"
Write-Host "Service name: $serviceName"
返回:
Hostname: myhost
Service name: myservice
这可能是什么原因?
谢谢, 罗马
答案 0 :(得分:1)
进一步挖掘,我自己找到了答案 - 需要使用-argumentlist
$hostname1 = "myhost"
$serviceName = "myservice"
Write-Host "Hostname: $hostname1"
Write-Host "Service name: $serviceName"
Invoke-Command -ComputerName $hostname1 -ScriptBlock {
Stop-Service -Name $args[0] -Force
} -argumentlist $serviceName
答案 1 :(得分:0)
另一种解决方案
,请使用自动变量'$ using'。
$hostname1 = "myhost"
$serviceName = "myservice"
Write-Host "Hostname: $hostname1"
Write-Host "Service name: $serviceName"
Invoke-Command -ComputerName $hostname1 -ScriptBlock {
Stop-Service -Name $Using:ServiceName -Force
}