【发布时间】:2017-04-27 13:08:30
【问题描述】:
Invoke-Command 没有提取我的变量吗?
我被这个抓住了。我可以用一双额外的眼睛!
我从远程机器中提取服务并按编号分配它们,然后根据用户输入将停止/启动传递给远程机器。我得到一个关于我的变量的论点。
请原谅我的代码设置我是新的,我写然后我清理。出于隐私考虑,一些服务和名称已被删除。
代码::
$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
错误::
无法将参数绑定到参数“名称”,因为它为空。 + CategoryInfo : InvalidData: (:) [Stop-Service], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.StopServiceCommand
无法将参数绑定到参数“名称”,因为它为空。 + CategoryInfo : InvalidData: (:) [Start-Service], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.StartServiceCommand
【问题讨论】:
-
不,
Invoke-Command没有远程变量(脚本的动态特性意味着通常很难知道哪些是远程的)所以远程端没有变量$svc当脚本块通过时。从 3.0 开始,您可以使用$using修复此问题。见about_Remote_Variables。 -
感谢 Jeroen,我在 Invoke 末尾传递了一个 -ArgumentList $Service 来调用我的变量。我还想将 $svc.name 捕获到一个单独的变量中以供以后使用。现在每行看起来像这样 $svc = $menu |其中 {$_item -eq $r} $Service = $svc.name Invoke-Command -ComputerName $Fname -ScriptBlock {Start-Service -Name $args[0]} -ArgumentList $Service