1

Here my script :

Relance de Service sur machine distante

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?

1
  • 1
    Invoke-Command -Session $session -ScriptBlock {param($Service) $A = get-service -Name $Service} -ArgumentList $Service ? Commented Jul 19, 2018 at 7:21

1 Answer 1

2

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:

Sign up to request clarification or add additional context in comments.

2 Comments

I'm new here, so i don't know how to do that.
I did it. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.