Invoke-Command无法绑定参数错误

时间:2016-12-12 16:01:04

标签: powershell invoke-command

Invoke-Command是不是拉我的变量?

我抓住了这一个。我可以用一双xtra眼睛!

我从远程计算机中提取服务并按编号分配服务,然后根据用户输入将停止/启动传递给远程计算机。我在我的变量上得到一个论点。

请原谅代码设置我是新的,然后我写,然后我清理。一些服务和名称已被删除以保护隐私。

代码::

$prepend = "ssssssssss"
$append = "sss"
$Fprepend = "tttttttt"
$Fappend = "tt"
$sitenumber = Read-Host 'What is the site number? ex. 1111'
 $name = $prepend + $sitenumber + $append  
 $Fname = $Fname = $Fprepend + $sitenumber + $Fappend

      $global:i=0
Get-service -Name Service,Instance,Server,Integration,Data,Message,FTP,Provider -ComputerName $name |
Select @{Name="Item";Expression={$global:i++;$global:i}},Name -OutVariable menu | Format-Table -AutoSize

$r = Read-Host "Select a service to restart by number"
$svc = $menu | where {$_.item -eq $r}

Write-Host "Restarting $($svc.name)" -ForegroundColor Green

Invoke-Command -ComputerName $Fname -ScriptBlock {Stop-Service -Name $svc.name -Force}
 sleep 3
Invoke-Command -ComputerName $Fname -ScriptBlock {Start-Service -Name $svc.name -Force}
Get-service -Name $svc.name -Computername $name

错误::

无法将参数绑定到参数'名称'因为它是null。     + CategoryInfo:InvalidData :( :) [Stop-Service],ParameterBindingValidationException     + FullyQualifiedErrorId:ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.StopServiceCommand

无法将参数绑定到参数'名称'因为它是null。     + CategoryInfo:InvalidData :( :) [Start-Service],ParameterBindingValidationException     + FullyQualifiedErrorId:ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.StartServiceCommand

1 个答案:

答案 0 :(得分:0)

我修改了代码,现在工作正常。 您遇到的问题是因为在脚本块中, $ svc 没有保留任何值,因为它甚至不在范围内。要使其在范围内,您必须作为 ArgumentList 传递,并且必须在块内作为 param 启动。这就是为什么你得到 Null

使用以下代码。我刚刚修改了Invoke部分

$prepend = "ssssssssss"
$append = "sss"
$Fprepend = "tttttttt"
$Fappend = "tt"
$sitenumber = Read-Host 'What is the site number? ex. 1111'
 $name = $prepend + $sitenumber + $append  
 $Fname = $Fname = $Fprepend + $sitenumber + $Fappend

      $global:i=0
Get-service -Name Service,Instance,Server,Integration,Data,Message,FTP,Provider -ComputerName $name |
Select @{Name="Item";Expression={$global:i++;$global:i}},Name -OutVariable menu | Format-Table -AutoSize

$r = Read-Host "Select a service to restart by number"
$svc = $menu | where {$_.item -eq $r}

Write-Host "Restarting $($svc.name)" -ForegroundColor Green
# You have to pass the $svc as an argumentlist and the same has to be initiated as param inside the script block.
Invoke-Command -ComputerName $Fname -ScriptBlock {param($svc)Stop-Service -Name $svc.name -Force} -ArgumentList $svc
 sleep 3
Invoke-Command -ComputerName $Fname -ScriptBlock {param($svc)Start-Service -Name $svc.name -Force} -ArgumentList $svc
Get-service -Name $svc.name -Computername $name

希望你现在明白这个问题。