0

I hope this is in the correct place. I know this question has been asked a lot before but I can't quite find what I need.

I am looking for a script to run on several remote servers at once to stop a particular service if it is running and set it to manual startup.

That bit is the easy part, I would also like it to feedback to me what task its doing and then check the service again after to confirm its stopped and set to manual.

This is what I have so far.

##Get user credentials
$credtentials = Get-Credential


##Services
$servicename = 'Spooler'
##Server List
$server = 'myserver'

$service = Get-Service -Name $servicename -ComputerName $server

if ($service.StartType -eq 'Automatic') {
    $service | Set-Service -StartupType Manual
}

Is anyone able to contribute to this please?

3

1 Answer 1

1

Create an array variable ($Servers) for the server names and pass that to the -ComputerName variable of invoke-command. This runs the PowerShell logic within a -ScriptBlock against each machine listed in the array .

This also uses the credential you enter in and with that credential it runs the invoked commands within the script block as that security context against all those servers.

It will set the StartType to Manual if it's set to Automatic, and it will stop the service if its status if Running. Afterwards, it will output the remote server name, the service Name, the Status, and the StartType.

Please note this assumes the credential you put into the $credential variable has admin access to each server you run the remote commands against; adjust $servers list accordingly per run.

PowerShell

$credentials = Get-Credential;
$Servers = "server0004","server0982";
$servicename = 'Spooler';

Invoke-Command -ComputerName $Servers -ScriptBlock {
    $service = Get-Service -Name $args[0];
    If($service.StartType -eq 'Automatic'){$service | Set-Service -StartupType Manual};
    If($service.Status -eq 'Running'){$service | Stop-Service -Force};
    $service = Get-Service -Name $args[0];
    $service | Select @{n="Server"; e={$env:COMPUTERNAME}}, Status, Name, StartType | FT
    } -ArgumentList $servicename -Credential $credentials;

Output

Server      Status Name    StartType
------      ------ ----    ---------
server0982 Stopped Spooler    Manual



Server      Status Name    StartType
------      ------ ----    ---------
server0004 Stopped Spooler    Manual

Supporting Resources

  • Invoke-Command

    -ArgumentList Object[]

    Set local variables in the command. The variables in the command are replaced by these values before the command is run on the remote computer. Enter the values in a comma-separated list. Values are associated with variables in the order that they are listed. The alias for ArgumentList is "Args".

  • Stop-Service

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.