

# Per far scrivere il ritorno dalla chiamata di IIS nel file di log ho creato la schedulazione entrando con 
# l'utente stesso (Steamware) che esegue lo script e ho fatto import della schedulazione ( in ambiente ISE il log lo scrive )
# Ho messo anche permessi all'utente "Logon as batch job" ( vedi sotto )

# Utente messo in PowerUser e permessi scrittura cartella Steamware

# Logon as batch job policy is set for the user. This policy is accessible by opening the Control Panel, Administrative Tools, 
# and then Local Security Policy -> Local Policy -> User Rights Assignment -> then Logon as batch job.

# Task Security Context
# https://forsenergy.com/en-us/taskscheduler/html/a922c2b5-6a43-4503-ab7f-4f3d77b3cc8a.htm

# Mod. 2022-05-17 Inizio ...

Remove-Variable * -ErrorAction SilentlyContinue  # pulisco variabili x ISE

# avvio stopwatch
$stopwatch =  [system.diagnostics.stopwatch]::StartNew()

$FolderName="c:\Steamware\Logs"
$Logfile = Join-Path $FolderName "\GPW_CheckScadenzeLic.log"
$Server  = "liman.egalware.com"
$callUri = "https://liman.egalware.com/ELM.API/api/licenza/CheckScadenze"
$ErrorActionPreference = "Stop"

Function LogWrite
{
   Param ([string]$logstring)
   
   $Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss.fff")
   Add-content $Logfile -value "$Stamp $logstring"
}

if (Test-Path $FolderName) {
    # Write-Host "Folder Exists"
}
else
{   #PowerShell Create directory if not exists
    New-Item $FolderName -ItemType Directory
    Write-Host "Folder Created successfully"
}

LogWrite("Start Check Licenses process...")

# # TEST CONNECTION 
# LogWrite("Start Ping --> $Server ...") 
# Test-Connection -ComputerName $Server -ErrorAction SilentlyContinue | Format-Table -AutoSize | Out-File -encoding utf8 $Logfile -Append     # se non lo trova prosegue cmq

try { # vera chiamata
  LogWrite("Effettuo chiamata target...")
  $Response = Invoke-WebRequest -URI $callUri -UseBasicParsing
  LogWrite($Response)
}
catch {
  $Response = 'Call ERROR ...'
  LogWrite($Error[0])
}
finally
{
  LogWrite("*** END Call ***")
}

# fermo stopwatch e conteggio...
$stopwatch.Stop()
$durata = $stopwatch.Elapsed.TotalSeconds
& "C:\Program Files\Zabbix Agent\zabbix_sender.exe" -z zabproxy.ufficio -s "W2022-IIS04" -k LiMan.Lic -o $durata
LogWrite("Durata esecuzione: $durata")
