I am writing a script that will be passing in two variables and a csv file to change services on a computer listed in csv file.
the command will be in this format: ex. start SQLService or stop PBIService
given csv file:
server,serviceserver1,SQLService
server2,PBIService
server3,PBIService
param($task, $service) #arguments from cmd line input
if($task -eq "start")
{
Set-Variable -Name "task" -Value "running"
}
elseif($task -eq "stop")
{
Set-Variable -Name "task" -Value "stopped"
}
if($service -eq "SQLService")
{
Set-Variable -Name "SQLsvc" -Value "SQLService"
}
elseif($service -eq "PBIService")
{
Set-Variable -Name "PBIsvc" -Value "PBIService"
}
Import-CSV .\csvfile.csv |
ForEach {
if($_.service -eq "SQLService")
{
$getService = Get-Service $SQLsvc -ComputerName $_.Server
$oldstatus = $getService.status
$getService |
Set-Service -Status $task -PassThru |
Select MachineName, Name, Status,
@{n='OldStatus';e={$oldStatus}}
}
elseif($_.Service -eq "PBIService")
{
$getService = Get-Service $PBIsvc -ComputerName $_.Server
$oldstatus = $getService.status
$getService |
Set-Service -Status $task -PassThru |
Select MachineName, Name, Status,
@{n='OldStatus';e={$oldStatus}}
}
} |
tee output.txt
However, when i run this for some reason it affects ALL services…
MachineName Name Status OldStatus
----------- ---- ------ ---------
server1 SQLService Running Running
server2 PBIService Running Running
Set-Service : Service 'Microsoft Monitoring Agent Audit Forwarding (AdtAgent)' cannot be started due to the following
error: Cannot start service AdtAgent on computer 'server3'.
+ Set-Service -Status $task -PassThru |
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Set-Service], Se
rviceCommandException
+ FullyQualifiedErrorId : CouldNotStartService,Microsoft.PowerShell.Commands.SetServiceCommand
server3 AdtAgent Stopped ...ed...}
Set-Service : Service 'AllJoyn Router Service (AJRouter)' cannot be started due to the following error: Cannot start
service AJRouter on computer 'server3'.
+ Set-Service -Status $task -PassThru |
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Set-Service], Se
rviceCommandException
+ FullyQualifiedErrorId : CouldNotStartService,Microsoft.PowerShell.Commands.SetServiceCommand
server3 AJRouter Stopped ...ed...}
Also, why if i command start SQLService, PBIService also starts? the condition isnt working properly for some reason… the only affected server and service in this case should server1 because per if condition, that server has the service = SQLService