Reputation: 11
Here my script :
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser -Force
$passwd = ConvertTo-SecureString -AsPlainText -Force -String PASSWORD #Remplacer 'Password' par votre Mot de passe Datacenter
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "LOGIN",$passwd #Remplacer 'login' par votre login datacenter
$Server = Read-Host -Prompt 'Veuillez entrer le nom du serveur'
$session = New-PSSession -ComputerName $Server -Credential $cred
$Service = Read-Host -Prompt 'Veuillez entrer le nom du service'
Invoke-Command -Session $session -ScriptBlock {$A = get-service -Name $Service}
if ($A.Status -eq "Stopped") {$A.start()}
elseIf ($A.status -eq "Running") {Write-Host -ForegroundColor Yellow $A.name "is running"}
Get-PSSession | Remove-PSSession
My script is almost working, but i've got an 'error' or i missed something. When i use prompt to get the server name $Server and put it in the variable everything is ok. But when i use prompt to get the Service name in a variable $Service, and use get-service -name $Service, it doesn't work. Why? Could you help me please?
Upvotes: 1
Views: 1708
Reputation: 5227
Your issue is not with Get-Service
but with Invoke-Command
. The variable $Service
you use is not passed from your session to the invoked command. There are multiple options to do this:
By param (as Paxz mentioned in comments):
-ScriptBlock {param($Service) $A = get-service -Name $Service} -ArgumentList $Service
By using:
:
-ScriptBlock {$A = get-service -Name $using:Service}
By argument directly:
-ScriptBlock {$A = get-service -Name $args[0]} -ArgumentList $Service
Also keep in mind the scope of variables while trying to restart them.
Some useful links to check when it comes to passing variables to remote sessions:
Upvotes: 2