i'm trying to create script that would loop all services listed in txt file, check if service startup type is right (if not change it) and start service if needed. I'm not that good with Powershell and would not really find anything usefully from Google.
My text file:
Service A
Service B
Service C
Service D
Service E
My current script look currently like this and at the moment I was able to print every single service from text file but lack information from next steps.
$services = Get-Content .\services.txt
## Pass each service object to the pipeline and process them with the Foreach-Object cmdlet
foreach ($service in $services) {
Get-Service $service | Select-Object -Property Name, StartType, Status, DisplayName
}
Hard thing is that every service don't have same startup type and status so it more complicated e.g
So if service A are not Manual and running, script would change them and give information about change (write-host?).
I know what I can change Service startup type and Status with command set-service and list status with get-service but my skills are not enough yet to set that in script. Don't know if this even possible this way or are they better ways to do this.
It would be better to change your services text file to a Csv file where you can not only list the service's Name, but also the desired StartType and Status like:
Service,StartType,Status Service A,Manual,Running Service B,Automatic,Running Service C,Manual,Stopped
Then you could code it something like
Import-Csv -Path .\services.csv | ForEach-Object {
$changed = $false
$service = Get-Service -Name $_.Service
if ($service.StartType -ne $_.StartType) {
Write-Host "Changing StartType for service $($service.Name)" -ForegroundColor Yellow
$service | Set-Service -StartupType $_.StartType
$changed = $true
}
if ($service.Status -ne $_.Status) {
Write-Host "Changing Status for service $($service.Name)" -ForegroundColor Yellow
$service | Set-Service -Status $_.Status
$changed = $true
}
# refresh the info if you changed anything above
if ($changed) { $service = Get-Service -Name $_.Service }
# write out current status
Write-Host "Service: $($service.Name) - StartType: $($service.StartType) - Status: $($service.Status)"
}