Is Invoke-Command not pulling my variables?
Im caught on this one. I could use an xtra set of eyes!
Im pulling services from a remote machine and assigning them by number then passing a stop / start to the remote machine based off user input. Im getting a argument on my variable.
Please forgive the code setup Im new and I write then I clean. Some services and names have been removed for privacy.
Code::
$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
Error::
Cannot bind argument to parameter 'Name' because it is null. + CategoryInfo : InvalidData: (:) [Stop-Service], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.StopServiceCommand
Cannot bind argument to parameter 'Name' because it is null. + CategoryInfo : InvalidData: (:) [Start-Service], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.StartServiceCommand
Invoke-Commanddoes not remote variables (the dynamic nature of scripts means it would be really hard to know which ones to remote in general) so there is no variable$svcon the remote end when the scriptblock is passed. From 3.0 onwards, you can fix this with$using. Seeabout_Remote_Variables. - Jeroen Mostert