Hello,
I am new to PS,but have been trying to learn for sometime now.
I’ve made s script that would
1.On a new build server, take the important services and export them to c:\Services.txt.
2.Then keep this task that would run on the server (PS script in scheduled task) to check and verify and possibly try to restart it if found not running.
Problem.
1.The script executes perfectly in ISE.( after re-opening multiple times, just to clear any cached vars )
- Script fails badly in Console. Tried STA mode also. ( after re-opening multiple times, just to clear any cached vars )
Script :
While($true)
{
Write-Output "Checking Services .........."
Sleep 2
$Running =""
$Running = Get-Service |Where { $_.Status -eq "Running"} | Select-Object Name
Write-Output $Running | Out-File C:\Users\xxxxx\Scripts\services1.txt
$failed =""
$failed = Compare-Object (Get-Content C:\Users\xxxxx\Scripts\services.txt) -DifferenceObject (Get-Content C:\Users\xxxxxx\Scripts\services1.txt) | where {$_.SideIndicator -eq "<="}| Select-Object InputObject -ExpandProperty InputObject
If($failed.length -ne "0")
{
foreach($fail in $failed)
{
$fail=$fail.trim()
Write-Output "Service failed : $fail : Attempting to restart!!"
Start-Service -Name $fail -Verbose
sleep 2
Get-Service -Name $fail
}
}
else
{
Write-Output "Services are running as designed"
}
sleep 1
}
Console Output
" .\AutoServiceBot.ps1
Checking Services …
Service failed : Name : Attempting to restart!!
Start-Service : Cannot find any service with service name "Name".
At C:\Users\xxxxx\Scripts\AutoServiceBot.ps1:26 char:9
-
Start-Service -Name $fail -Verbose -
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~- CategoryInfo : ObjectNotFound: (Name:String) [Start-Service], ServiceCommandException
- FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.StartServiceCommand
==========================================================================================================================
ExpandProperty has to be removing the below from output so that it could be compared.(please let me know if i were to be wrong anywhere)
"
Name
"
Any help would be higly appreciated.
Regards.