Home > Enterprise >  Compare all services on the local computer with referent list of allowed services stored in .html fi
Compare all services on the local computer with referent list of allowed services stored in .html fi

Time:03-23

I need a script in powershell that will check the status of all services on the local computer and compare with the reference list of allowed services stored in the .html file I created earlier. After the comparison, the script will stop all services running on the computer that are not listed in the reference file.

CodePudding user response:

First i would like to say this code has no validation and will not work well with other html tables. And it is not optimized at all.

$ServicesFromHTML = (gc .\services.htm | where {$_ -match '^<tr><td>(Name:|Status:|<hr>)'}) -replace "</?t(r|d)>","" -join ";" -replace ";<hr>;","`r`n" -replace "(Name:|Status:)","" | ConvertFrom-Csv -Delimiter ";" -Header "Name","Status"
$RunningServices = Get-Service | Where-Object {$_.Status -eq "Running"} | Select Name,Status
"Comparing services if they are currently running ("<=") or were running when exported ("=>")"
Compare-Object $RunningServices.Name $ServicesFromHTML.Name
$OnlyNowRunningServices = (Compare-Object $RunningServices.Name $ServicesFromHTML.Name | where {$_.SideIndicator -eq "<="}).InputObject
$OnlyNowRunningServices | foreach {"Trying to stop Service $_";Stop-Service $_}

For the future use CSV/XML/JSON export as you can import them quite easy. If you need something human readable to read in browser, then create it additionaly.

  • Related