'Version vom 14.12.2009

Set WshShell = Wscript.CreateObject("WScript.Shell")
Set FSO      = CreateObject("Scripting.FileSystemObject")
Set net      = Wscript.createObject("Wscript.network")
Set db1      = CreateObject("ADODB.Connection")
Dim Aktiv, Log, Logpfad


'**************************************************************
'Einstellungen
'**************************************************************
'Logs / Debug
Log=1                            'Bei 1 werden Logfiles erstellt. Bei 0 nicht
Logpfad="c:\"                    'Pfad für Logfile

'Für LightsOut
Aktion=1                         'Aktionen für Lightsout 0=nichts, 1=Standby, 2=Ruhezustand, 3=Herunterfahren

'Für Taskplaner
PLUser=      "Administrator"
PLPW=        "xxx"

'Für Mediaportal
CheckMP=     1                  'Zur Nutzung ohne Mediaportal =0 ; Mit MP = 1
SQLServer=  "Server\SQLEXPRESS"
SQLUser=    "sa"
SQLPW=      "MediaPortal"
DWH=        "MpTvDb"
Zeitdiff =  3                   'Minuten vor Aufnahmenbeginn aufwachen

'**************************************************************
'Start (diverse Einstellungen)
'**************************************************************
Aktiv=0        'Das muss so. Sobald ein Kriterium zum wachbleiben erfüllt ist, erhöht sich der Wert.
               'Ist der Wert am Ende des Scripts noch immer 0, dann wird Lightsout für Standby konfiguriert.
SingleStart    'Doppelausführung verhindern
setup          'Regestryeintrag anlegen
Taskliste      'Es wird unter c:\taskliste.txt eine Liste aller aktiven Programme erstellt.
               'Hieraus können die Suchbgriffe für die Programmprüfung übernommen werden.

'**************************************************************
'Beginn Hauptprogramm
'**************************************************************
Do while 1=1 ' Beginn Endlosschleige
logdatei "--- Start ---"
Aktiv=0

'**************************************************************
'Prüfen ob Programme online
'**************************************************************
'z.B.
'WSHCheckTask ("Notepad.exe")
WSHCheckTask ("flatster.exe")
WSHCheckTask ("iexplore.exe")

'**************************************************************
'Prüfen ob Rechner online
'**************************************************************
'z.B.
'WSHonline ("Buerorechner")
'WSHonline ("192.168.1.8")

'**************************************************************
'Befehl ausführen und Ergebnis durchsuchen
'**************************************************************
'z.B.
'cmdline "dir C:\","testdatei.txt"


'**************************************************************
'Mediaportal
'**************************************************************
if CheckMP=1 then
      'Task zum Aufwachen anlegen, wenn noch nicht vorhanden
      if not fso.fileexists("C:\WINDOWS\Tasks\MP_Aufnahmen.job") then
      intReturn = WshShell.Run("SCHTASKS /Create /ru "&lcase(net.computerName)&"\"&PLUser&" /RP "&chr(34)&PLPW&chr(34)&" /SC täglich /TN MP_Aufnahmen /TR C:\WINDOWS\system32\tasklist.exe /ST 00:00:00" , 1, true)
      msgbox "Der Task wurde neu angelegt. Bitte setzte bei dem automatischen Task 'MP_Aufnahmen' händisch die Option 'Computer zum Ausführen des Tasks reaktivieren'.",0,"Achtung"
      end if

      'Datenbankabfrage
      on error resume next 'Bei Fehler Script fortsetzen

      db1.Open("Driver={SQL Server};SERVER="&SQLServer&";Database="&DWH&";User ID="&SQLUser&";Password="&SQLPW)
      CheckFehler
      set rs1=db1.execute("select top 1 channel, programName, startTime, endTime, preRecordInterval, postRecordInterval , dateadd(mi, (preRecordInterval + "&Zeitdiff&") * -1, startTime) as Start from " & _
                          "	( " & _
                          "	select c.name as channel, s.programName, s.startTime, s.endTime, s.preRecordInterval, s.postRecordInterval  " & _
                          "	  from schedule s, channel c  " & _
                          "	 where s.scheduleType = '0' and c.idChannel = s.idChannel " & _
                          "	union " & _
                          "	select c.name as channel, s.programName, p.startTime, p.endTime, s.preRecordInterval, s.postRecordInterval  " & _
                          "	  from schedule s, program p, channel c  " & _
                          "	 where s.scheduleType = '1' and c.idChannel = s.idChannel and p.title = s.programName  " & _
                          "	   and CONVERT(varchar(8), p.startTime, 108) = CONVERT(varchar(8), s.startTime, 108) " & _
                          "	   and CONVERT(varchar(8), p.endTime, 108) = CONVERT(varchar(8), s.endTime, 108) " & _
                          "	union " & _
                          "	select c.name as channel, s.programName, p.startTime, p.endTime, s.preRecordInterval, s.postRecordInterval  " & _
                          "	  from schedule s, program p, channel c  " & _
                          "	 where s.scheduleType = '2' and c.idChannel = s.idChannel and p.title = s.programName  " & _
                          "	   and datediff(d, s.startTime, p.startTime) % 7 = 0 " & _
                          "	   and datediff(d, s.endTime, p.endTime) % 7 = 0 " & _
                          "	   and CONVERT(varchar(8), p.startTime, 108) = CONVERT(varchar(8), s.startTime, 108) " & _
                          "	   and CONVERT(varchar(8), p.endTime, 108) = CONVERT(varchar(8), s.endTime, 108) " & _
                          "	union " & _
                          "	select c.name as channel, s.programName, p.startTime, p.EndTime, s.preRecordInterval, s.postRecordInterval   " & _
                          "	  from schedule s, program p, channel c  " & _
                          "	 where s.scheduleType = '3' and p.title = s.programName and s.idChannel = p.idChannel and c.idChannel = s.idChannel " & _
                          "	union " & _
                          "	select c.name as channel, s.programName, p.startTime, p.EndTime, s.preRecordInterval, s.postRecordInterval  " & _
                          "	  from schedule s, program p, channel c  " & _
                          "	 where s.scheduleType = '4' and p.title = s.programName and c.idChannel = s.idChannel " & _
                          "	) as UA " & _
                          "where endTime > current_timestamp " & _
                          "order by startTime Asc")
      if err.number=0 then
          'Nur wenn kein Fehler aufgetreten ist, normales vorgehen
          if isdate(rs1("Start")) then 'Wenn Aufnahmen programmiert sind oder aktuelle eine läuft...
             if rs1("Start")<now() then
                'Es läuft gerade eine Aufnahme
                aktiv=aktiv+1
                Logdatei "aktive Aufnahme: "&rs1("channel")&" - "&rs1("programName")&" - Ende "&rs1("endTime")
                if "A"&WshShell.RegRead("HKCU\SOFTWARE\AxoNet Software GmbH\LightsOut\MP_Aufnahme")<>"A"&"01.01.2020" then
                   Logdatei "Set Taskplaner:  01.01.2020"
                   intReturn = WshShell.Run("SCHTASKS /change /ru "&lcase(net.computerName)&"\"&PLUser&" /RP "&chr(34)&PLPW&chr(34)&" /TN MP_Aufnahmen /ST 00:00 /SD 01/01/2020" , 1, true)
                   WshShell.RegWrite "HKCU\SOFTWARE\AxoNet Software GmbH\LightsOut\MP_Aufnahme","01.01.2020","REG_EXPAND_SZ"
                else
                   Logdatei "Taskplaner = 01.01.2020"
                end if
             else
               'Es ist eine Aufnahme geplant, ggf Starttask anlegen
                Logdatei "geplante Aufnahme: "&rs1("channel")&" - "&rs1("programName")&" - Start "&rs1("startTime")
                'wenn Task nicht schon angelegt wurde, anlegen
                  if "A"&WshShell.RegRead("HKCU\SOFTWARE\AxoNet Software GmbH\LightsOut\MP_Aufnahme")<>"A"&rs1("Start") then
                     Logdatei "Set Taskplaner: "&rs1("Start")
                     intReturn = WshShell.Run("SCHTASKS /change /ru "&lcase(net.computerName)&"\"&PLUser&" /RP "&chr(34)&PLPW&chr(34)&" /TN MP_Aufnahmen /ST "&right(rs1("Start"),8)&" /SD "&replace(left(rs1("Start"),10),".","/") , 1, true)
                     WshShell.RegWrite "HKCU\SOFTWARE\AxoNet Software GmbH\LightsOut\MP_Aufnahme",rs1("Start"),"REG_EXPAND_SZ"
                  else
                     Logdatei "Taskplaner = "&rs1("Start")
                  end if
             end if
          end if
      else  ' Fehlermeldung loggen, kein Standby
        CheckFehler
        aktiv=aktiv+1
      end if
      db1.close
      'Fehlerprüfung wieder aktivieren
      on error goto 0
end if

'**************************************************************
'Aktion nach X Minuten in LightsOut konfigurieren
'**************************************************************
if Aktiv=0 then
WshShell.RegWrite "HKLM\SOFTWARE\AxoNet Software GmbH\LightsOut\Action",Aktion,"REG_DWORD"
Logdatei "Set LightsOut = "&Aktion
else
WshShell.RegWrite "HKLM\SOFTWARE\AxoNet Software GmbH\LightsOut\Action","0","REG_DWORD"
Logdatei "Set LightsOut = 0 (keine Aktion)"
end if

wscript.sleep 5*60000 '5 Minuten / 1000 = 1 Sekunde
loop 'Wieder zum Schleifenanfang





Sub Setup
'**************************************************************
'Prüfen ob Registry schon besteht
'**************************************************************
on error resume next
  WshShell.RegRead("HKCU\SOFTWARE\AxoNet Software GmbH\LightsOut\MP_Aufnahme")
  if err.number<>0 then
   WshShell.RegWrite "HKCU\SOFTWARE\AxoNet Software GmbH\LightsOut\MP_Aufnahme","01.01.2020","REG_EXPAND_SZ"
  end if
on error goto 0
end sub


'**************************************************************
Sub SingleStart 'sobald gleiches Script bereits läuft,
                'wird das aktuelle Script beendet
'**************************************************************
  Anz = 0
  Const wbemFlagReturnImmediately = &h10
  Const wbemFlagForwardOnly = &h20
  Dim objWMIService : Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
  Dim colItems      : Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_Process", "WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly)
  Dim objItem
  For Each objItem In colItems
    If InStr( LCase( objItem.CommandLine), LCase( WScript.ScriptFullName ) ) > 0 Then
       Anz = Anz + 1
    End If
  Next
  if Anz>1 then
  wscript.quit
  end if

End Sub

'********************************************************************************************
Sub WSHCheckTask (textx) 'Sobald Task aktiv, wird Variable "Aktiv" und eins erhöht

  Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
  wbemFlagReturnImmediately = &h10:wbemFlagForwardOnly = &h20
  Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_Process", "WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly)
  For Each objItem In colItems
    if instr(lcase(objItem.CommandLine),lcase(textx))>0 then
    Aktiv=Aktiv+1
    Logdatei "Anwend aktiv:   "&textx
    end if
  Next
end Sub

'********************************************************************************************
Sub WSHonline (textx) 'Sobald Rechner aktiv, wird Variable "Aktiv" und eins erhöht
'********************************************************************************************
Set cPingResults = GetObject("winmgmts:{impersonationLevel=impersonate}//./root/cimv2"). ExecQuery("SELECT * FROM Win32_PingStatus WHERE Address = '" + textx + "'")
For Each oPingResult In cPingResults
	If oPingResult.StatusCode = 0 Then
	Aktiv=Aktiv+1
        Logdatei "IP aktiv:   "&textx
	End If
Next
end Sub

'********************************************************************************************
Sub Taskliste
'********************************************************************************************
  Set FileOut = fso.createTextFile(logpfad&"\taskliste.txt",True)
    Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
    wbemFlagReturnImmediately = &h10:wbemFlagForwardOnly = &h20
    Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_Process", "WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly)
      For Each objItem In colItems
        FileOut.WriteLine objItem.CommandLine&" "
      Next
  FileOut.Close
  Set FileOut = Nothing
End Sub

'-------------------------------------------------------------------------------
Sub LogDatei (LogTxt) '01.01.2007
'-------------------------------------------------------------------------------
if log=1 then
  on error resume next
  Set FileOut = fso.OpenTextFile( logpfad&"\WHS_Standby.log" , 8, true)
      FileOut.WriteLine Now()&"  "&LogTxt
      FileOut.Close
  Set FileOut = Nothing
  on error goto 0
end if
End Sub

'-------------------------------------------------------------------------------
sub cmdline(textx,texty)'
'-------------------------------------------------------------------------------
intReturn = WshShell.Run("cmd.exe /u /c "&textx&" >C:\tmp.txt" , 0, true)
Set FileIn = FSO.getFile("C:\tmp.txt")
set FileIn2 = FileIn.openAsTextStream(1,-1) '-1 = Unicode
set FileIn3 = FileIn.openAsTextStream(1,0) '0 = Ascii
  if instr(FileIn2.readall&FileIn3.readall,texty)>0 then
  Aktiv=Aktiv+1
  end if
fileIn2.close
fileIn3.close
fso.deletefile("c:\tmp.txt")
end sub

'**************************************************************
Sub CheckFehler
'**************************************************************
if err.number<>0 then
      logdatei "Fehler:" & Err.Description
      err.clear
end if
end sub